Ajax提交json格式数据

myAjax.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>

<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()">
    
    <script type="text/javascript" src="${pageContext.request.contextPath}/resources/scripts/jquery-1.8.3.min.js">script>
    
    <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);

    }

}

获取用户输入的数据

Ajax提交json格式数据_第1张图片


servlet接收到数据

Ajax提交json格式数据_第2张图片


servlet返回给客户端的数据

Ajax提交json格式数据_第3张图片

你可能感兴趣的:(ajax)