关闭

Ajax提交json格式数据

5300人阅读 评论(1) 收藏 举报
分类:

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返回给客户端的数据

这里写图片描述

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:20215次
    • 积分:550
    • 等级:
    • 排名:千里之外
    • 原创:35篇
    • 转载:2篇
    • 译文:0篇
    • 评论:10条
    文章分类
    最新评论