欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Ajax -- $.get() 方法解析 JSON 数据

程序员文章站 2024-01-30 10:59:28
...
<%@ 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>Insert title here</title>
<script type="text/javascript" src="script/jquery-1.7.2.js"></script>
<script type="text/javascript">

function RandomString(length) {
           var str = '';
           for ( ; str.length < length; str += Math.random().toString(36).substr(2) );
           return str.substr(0, length);
     }



     $(function(){
           $("#btn02").click(function(){
                //$.get(URL,data,success(response,status,xhr),dataType);
                $.get("AjaxJqueryGetServlet",{userName:'Jerry',passWord:'Jerry12345',date:RandomString(32)},function(data,status,xhr){
                     alert("后台返回数据: " + data.userName + ", " + data.passWord);
                     alert("状态: " + status);
                     alert("数据类型:" + xht);
                },"json");
           });
     });
</script>

</head>
<body>

     <center>
           <button id="btn01">$.post() 方法解析 JSON 数据</button><br/>
           <button id="btn02">$.get() 方法解析 JSON 数据</button>
     </center>

</body>
</html>
package com.atguigu.ajax.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.gson.Gson;

@WebServlet("/AjaxJqueryGetServlet")
public class AjaxJqueryGetServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Map<String,String> map = new HashMap<>();

        String userName = request.getParameter("userName");
        String passWord = request.getParameter("passWord");

        map.put("userName", userName);
        map.put("passWord", passWord);

        Gson gson = new Gson();
        String gsonMap = gson.toJson(map);

        PrintWriter out = response.getWriter();
        out.write(gsonMap);
    }
}