用jQuery和Json实现Ajax异步请求

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了用jQuery和Json实现Ajax异步请求相关的知识,希望对你有一定的参考价值。

这里有两个例子,一个是关于登录验证的,一个是异步加载数据的

1、regist.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP ‘regist.jsp‘ starting page</title>
    
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
    <script type="text/javascript" src="js/jquery-1.11.0.min.js"></script>
    <script type="text/javascript">
        $(function(){
            $("#username").blur(function(){
                $.ajax({
                    url:"checkUsername",
                    data:{"name":$("#username").val()},
                    success:function(data){
                        //alert(data);
                        var src = eval("("+data+")");
                        $("#sty").html(src.msg);
                    }
                });
            });
            
            
            $(":button").click(function(){
                $.ajax({
                    url:"findAll",
                    success:function(data){
                        $("tr").remove("tr:not(:eq(0))");
                        //alert(data);
                        var src = eval("("+data+")");
                        var table = $("table");
                        for(var i=0;i<src.length;i++){
                            //alert(src[i].name);
                            var tr = $("<tr></tr>");
                            var cell1 = $("<td>"+src[i].name+"</td>");
                            var cell2 = $("<td>"+src[i].sex+"</td>");
                            var cell3 = $("<td>"+src[i].age+"</td>");
                            cell1.appendTo(tr);
                            cell2.appendTo(tr);
                            cell3.appendTo(tr);
                            tr.appendTo(table);
                        }
                    }
                });
            });
            
        });
    </script>

  </head>
  
  <body>
    <form action="registAction">
        用户名:<input type="text" name="username" id="username"/><span id="sty"></span><br/>
        密码:<input type="password" name="pwd" id="pwd"/><br/>
        <input type="submit" value="注册"/>
    </form>
    <input type="button" value="查看全部"/><br/>
    <table>
        <tr>
            <td>姓名</td>
            <td>性别</td>
            <td>年龄</td>
        </tr>
    </table>
  </body>
</html>

2、导入JSON的必须包

技术分享

3、CheckUsername.java

package com.cn.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.JSONObject;

public class CheckUsername extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        this.doPost(request, response);
        
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        
        String username = request.getParameter("name");
        
        /*
         * json格式
         * {"name":"jack","age":"18"}
         */
        //String msg = "";

        //创建json对象
        JSONObject job = new JSONObject();
        
        if(username.equals("jack")){
            //msg = "{\\"msg\\":\\"当前用户已存在不可注册\\"}";
            job.put("msg", "当前用户已存在不可注册");
        }else{
            //msg = "{\\"msg\\":\\"当前用户可注册\\"}";
            job.put("msg", "当前用户可注册");
        }
        
        //out.print(msg);
        out.print(job);
        out.flush();
        out.close();
    }

}

4、User.java

package com.cn.pojo;

public class User {

    private String name;
    private String sex;
    private int age;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getSex() {
        return sex;
    }
    public void setSex(String sex) {
        this.sex = sex;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public User() {
        super();
        // TODO Auto-generated constructor stub
    }
    public User(String name, String sex, int age) {
        super();
        this.name = name;
        this.sex = sex;
        this.age = age;
    }
}

5、FindAll.java

package com.cn.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 FindAll extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        this.doPost(request, response);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        
        //json数组
        //[{"name":"jack","sex":"男","age":"18"},{"name":"lily","sex":"女","age":"17"},{"name":"tom","sex":"男","age":"18"}]
        
        //json对象
        JSONObject obj1 = new JSONObject();
        obj1.put("name", "jack");
        obj1.put("sex", "男");
        obj1.put("age", "18");
        
        JSONObject obj2 = new JSONObject();
        obj2.put("name", "lily");
        obj2.put("sex", "女");
        obj2.put("age", "17");
        
        JSONObject obj3 = new JSONObject();
        obj3.put("name", "tom");
        obj3.put("sex", "男");
        obj3.put("age", "18");
        
        //创建json数组
        JSONArray ja = new JSONArray();
        ja.add(obj1);
        ja.add(obj2);
        ja.add(obj3);
        
        out.print(ja);
        out.flush();
        out.close();
    }

}

 

以上是关于用jQuery和Json实现Ajax异步请求的主要内容,如果未能解决你的问题,请参考以下文章

现需要使用 jQuery 代码实现 ajax 请求,详细信息如下

JQuery实现AJAX异步请求实现省市联动(数据传输格式为json)

什么是Ajax ,异步,同步,JSON,XMLHttpRequest对象,什么是JSON,使用JQuery实现Ajax

08-最简洁易懂的Ajax+Json+JQuery+案例演示知识整理

jQuery ajax请求struts action实现异步刷新

JQuery实现AJAX异步请求实现省市联动(数据传输格式为xml)