Ajax結合Json進行交互數據(四)


<%@ 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">
    //json對象
    function loadInfo(){
        var xmlHttp;
        if(window.XMLHttpRequest){
            xmlHttp=new XMLHttpRequest();
        }else{
            xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlHttp.onreadystatechange=function(){
            if(xmlHttp.readyState==4 && xmlHttp.status==200){
                alert(xmlHttp.responseText);
                var dataObj=eval("("+xmlHttp.responseText+")");//得到的是json對象
                alert(dataObj.name);//因為是json對象,所以能點屬性
                alert(dataObj.age);
                document.getElementById("name").value=dataObj.name;
                document.getElementById("age").value=dataObj.age;
            }
        };
        xmlHttp.open("get", "getAjaxInfo?action=jsonObject", true);
        xmlHttp.send();
    }
    //json數組
    function loadInfo2(){
        var xmlHttp;
        if(window.XMLHttpRequest){
            xmlHttp=new XMLHttpRequest();
        }else{
            xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlHttp.onreadystatechange=function(){
            if(xmlHttp.readyState==4 && xmlHttp.status==200){
                alert(xmlHttp.responseText);
                var dataObj=eval("("+xmlHttp.responseText+")");
                var st=document.getElementById("studentTable");
                alert(dataObj.students.length);
                var newTr; //
                var newTd0; // 第一列
                var newTd1; // 第二列
                var newTd2; // 第三列
                for(var i=0;i<dataObj.students.length;i++){
                    var student=dataObj.students[i];
                    newTr=st.insertRow();
                    newTd0=newTr.insertCell();
                    newTd1=newTr.insertCell();
                    newTd2=newTr.insertCell();
                    newTd0.innerHTML=student.name;
                    newTd1.innerHTML=student.age;
                    newTd2.innerHTML="語文:"+student.score.chinese+",數學:"+student.score.math+",英語:"+student.score.english;
                }
            }
        };
        // xmlHttp.open("get", "getAjaxInfo?action=jsonArray", true);
        xmlHttp.open("get", "getAjaxInfo?action=jsonNested", true);
        xmlHttp.send();
    }
</script>
</head>
<body>
<div style="text-align: center;">
    <div><input type="button" onclick="loadInfo()" value="Ajax獲取信息"/>&nbsp;&nbsp;姓名:<input type="text" id="name" name="name" />&nbsp;&nbsp;年齡:<input type="text" id="age" name="age" /></div>
    <div style="margin-top: 20px;">
        <input type="button" onclick="loadInfo2()" value="Ajax獲取信息2"><br/>
        <table id="studentTable" align="center" border="1px;" cellpadding="0px;">
            <tr>
                <th>姓名</th><th>年齡</th><th>得分</th>
            </tr>
        </table>
    </div>
</div>
</body>
</html>
package com.wp.servlet

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 net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class GetAjaxInfoServlet extends HttpServlet {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    @Override
    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        String action = request.getParameter("action");
        if ("jsonObject".equals(action)) {
            this.getJsonObject(request, response);
        } else if ("jsonArray".equals(action)) {
            this.getJsonArray(request, response);
        } else if ("jsonNested".equals(action)) {
            this.getJsonNested(request, response);
        }

    }

    /**
     * json對象
     * 
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    private void getJsonObject(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        // String resultJson="{\"name\":\"張三\",\"age\":22}";//斜杠在這里是轉義
        JSONObject resultJson = new JSONObject();
        resultJson.put("name", "張三");
        resultJson.put("age", 22);
        out.println(resultJson);
        out.flush();
        out.close();
    }

    /**
     * 簡單的json數組
     * 
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    private void getJsonArray(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        JSONObject resultJson = new JSONObject();
        JSONArray jsonArray = new JSONArray();
        JSONObject jsonObject1 = new JSONObject();
        jsonObject1.put("name", "張三");
        jsonObject1.put("age", 22);
        JSONObject jsonObject2 = new JSONObject();
        jsonObject2.put("name", "李四");
        jsonObject2.put("age", 23);
        JSONObject jsonObject3 = new JSONObject();
        jsonObject3.put("name", "王五");
        jsonObject3.put("age", 24);
        jsonArray.add(jsonObject1);
        jsonArray.add(jsonObject2);
        jsonArray.add(jsonObject3);

        resultJson.put("students", jsonArray);
        out.println(resultJson);
        out.flush();
        out.close();
    }

    /**
     * 多重json嵌套
     * 
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    private void getJsonNested(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out = response.getWriter();

        JSONObject resultJson = new JSONObject();// 創建最后結果的json

        JSONArray jsonArray = new JSONArray();// json數組
        JSONObject jsonObject1 = new JSONObject();// json對象
        jsonObject1.put("name", "張三");
        jsonObject1.put("age", 22);

        JSONObject scoreObject1 = new JSONObject();
        scoreObject1.put("chinese", 90);
        scoreObject1.put("math", 100);
        scoreObject1.put("english", 80);
        jsonObject1.put("score", scoreObject1);

        JSONObject jsonObject2 = new JSONObject();
        jsonObject2.put("name", "李四");
        jsonObject2.put("age", 23);

        JSONObject scoreObject2 = new JSONObject();
        scoreObject2.put("chinese", 70);
        scoreObject2.put("math", 90);
        scoreObject2.put("english", 90);
        jsonObject2.put("score", scoreObject2);

        JSONObject jsonObject3 = new JSONObject();
        jsonObject3.put("name", "王五");
        jsonObject3.put("age", 24);

        JSONObject scoreObject3 = new JSONObject();
        scoreObject3.put("chinese", 80);
        scoreObject3.put("math", 60);
        scoreObject3.put("english", 90);
        jsonObject3.put("score", scoreObject3);
        // {"score":{"chinese":80,"math":60,"english":90}}
        jsonArray.add(jsonObject1);
        jsonArray.add(jsonObject2);
        jsonArray.add(jsonObject3);
        // {"name":"王五","age":24,"score":{"chinese":80,"math":60,"english":90}}
        resultJson.put("students", jsonArray);// "students":[數組]
        // {"student":[{"name":"王五","age":24,"score":{"chinese":80,"math":60,"english":90}}]}
        out.println(resultJson);
        out.flush();
        out.close();
    }
}

 ajax通過XMLHttpRequest的open和send方法進行請求,servlet端就是一個服務器端在接收請求后,通過response.getWriter()得到輸出字符流,然后在html頁面上通過XMLHttpRequest的responseText來得到響應的信息。

 

Java小生店鋪:

Pc端:http://shop125970977.taobao.com/index.htm

手機端:搜索 java小生店鋪

希望店鋪的資料能幫助到你!!!

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM