Ajax提交json格式数据

前端之家收集整理的这篇文章主要介绍了Ajax提交json格式数据前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

myAjax.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<Meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>ajax提交数据</title>
</head>
<body>
    <input id="username" type="text">
    <input type="submit" value="提交" onclick="test()">
    <!-- 引入jq类库 -->
    <script type="text/javascript" src="${pageContext.request.contextPath}/resources/scripts/jquery-1.8.3.min.js"></script>
    <!-- ajax提交 -->
    <script type="text/javascript"> function test(){ var my_username = $('#username').val(); var username = {'username': my_username}; var contextPath = '${pageContext.request.contextPath}'; alert(username.username); $.ajax({ type: "post",url: contextPath+"/myAjaxController",data: username,dataType: "json",success: function(msg){alert( msg );} //操作成功后的操作!msg是后台传过来的值  }); } </script>

</body>
</html>

myAjaxController.java

package com.hongyewell.ajax;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;

public class myAjaxController extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doPost(HttpServletRequest request,HttpServletResponse response) 
            throws ServletException,IOException {
        //接收数据
        request.setCharacterEncoding("utf-8");
        String username = request.getParameter("username");
        System.out.println(username);
        //返回数据
        String flag = "ok";
        PrintWriter out = response.getWriter();
        Gson gson = new Gson();
        String flagJson = gson.toJson(flag);
        out.write(flagJson);

    }

}

获取用户输入的数据


servlet接收到数据


servlet返回给客户端的数据

原文链接:https://www.f2er.com/ajax/162705.html

猜你在找的Ajax相关文章