AJAX请求,返回json进行页面绑值

  • 后台 controller

      @RequestMapping(value = "backjson.do",method=RequestMethod.POST,
    produces = "application/json;charset=UTF-8")
    @ResponseBody
    public JSONObject logout(HttpServletRequest request, HttpServletResponse response) {
    String Name = request.getParameter("name");
    String Phone = request.getParameter("phone");
    System.out.println(Name);
    System.out.println(Phone);
    System.out.println("进行返回json");
    String jsonStr = "{\"meta\":{\"success\":true,\"message\":\"OK\"},\"data\":\"退出成功\"}";
    JSONObject jsonObj = JSONObject.fromObject(jsonStr);
    return jsonObj;
    }
  • 前台代码:

    index.html

      <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>去往含有ajax的页面</title>
    </head>
    <body>
    <a href="queryList.html"><button type="button">点我!</button></a>
    </body>
    </html>

    queryList.html

      <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>AJAX请求,返回json进行页面绑值</title>
    </head>
    <script src="js/jquery.js"></script>
    <script>
    var name = "测试"; //测试与后台的连通性
    var phone = "1234";
    /* ajax请求 */
    $.ajax({
    url : "http://localhost:8080/Ajax_demo/backjson.do",
    type : "post",
    data : {
    "name" : name,
    "phone" : phone,
    },
    dataType : "json",
    success : function(data) {
    //alert(data);
    //console.log(data);
    //alert(data.meta.message);
    for ( var key in data) {
    var html = '<table border=1>';
    if (key == "meta") {
    for ( var key1 in data[key]) {
    console.log(data[key][key1]);
    //alert(key1+":"+data[key][key1]);
    var obj = data[key][key1];
    html += '<tr>'
    html += '<td>' + key1 + ":" + '</td>';
    html += '<td>' + obj + '</td>';
    html += '</tr>'
    }
    html += '</table>';
    console.log(html);
    $('#div1').append(html);
    } //赋值到表格与div
    //$("#table tr").eq(1).find("td").html("111"); //添加到第一行
    $("#td1").html(data[key].success); //绑定数据
    $("#td2").html(data[key].message);
    $(".top").val("1234"); //给input表单绑定数据
    $(".bottom").html("1234"); //给div绑定数据
    $(".foot").html(key + ":" + data[key]); //给div绑定数据
    //alert(key+":"+data[key]);
    }
    }
    });
    </script>
    <body>
    测试
    <hr width="100%">
    <br />
    <div id="div1"></div>
    <hr width="100%">
    <br />
    <table border="1" id="table">
    <tr>
    <td>success:</td>
    <td id="td1"></td>
    <td>message:</td>
    <td id="td2"></td>
    </tr> <!-- <tr>
    <td></td> <td></td>
    <td></td> <td></td>
    </tr> -->
    </table>
    <hr width="100%">
    <br />
    <input type="text" class="top" /> <hr width="100%">
    <br />
    <div class="bottom"></div>
    <hr width="100%">
    <br />
    <div class="foot"></div>
    </body>
    </html>
05-06 23:47