jquery中ajax的使用(java)

Posted H.U.C-王子

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了jquery中ajax的使用(java)相关的知识,希望对你有一定的参考价值。

AJAX方式 

js:界面

var prjContextPath=‘<%=request.getContextPath()%>‘;
$(document).ready(function(){ 
    //===============GET==============================
    $("#username").blur(function(){ 
        $.ajax({ 
            type: "GET",     
            url: prjContextPath + "/zhuceAction!queryUserName.action?username=" + $("#username").val()+"&pwd="+$("#pwd").val(),
            dataType: "json",
            success: function(data) {
                if (data.success) { 
                     $("#usernamemsg").html("<font color=‘green‘>" + data.msg + "</font>");
                } else {
                    $("#usernamemsg").html("<font color=‘red‘>" + data.msg + "</font>");
                }  
            },
            error: function(jqXHR){     
               alert("发生错误:" + jqXHR.status);  
            }     
        });
    });
    
  //===============POST==============================
    $("#username").blur(function(){ 
        $.ajax({ 
            type: "POST",     
            url: prjContextPath + "/zhuceAction!queryUserName.action",
            data: {
                username: $("#username").val(), 
                pwd: $("#pwd").val()
            },
            dataType: "json",
            success: function(data){
                if (data.success) { 
                     $("#usernamemsg").html("<font color=‘green‘>" + data.msg + "</font>");
                } else {
                     $("#usernamemsg").html("<font color=‘red‘>" + data.msg + "</font>");
                }  
            },
            error: function(jqXHR){     
               alert("发生错误:" + jqXHR.status);  
            }    
        });
    });
});

调用的action中的方法:

注意:此action要继承BaseAction

public void queryUserName() throws IOException {

        System.out.println("username=" + user.getUsername());
        System.out.println("pwd=" + user.getPwd());
        // 去数据库中验证
        boolean flag = true;
        
        //形成JSON串
        String  html = "";
        if (flag) {
            html = "{\"success\":1,\"msg\":\"用户名,可以使用!\"}";
        } else {
            html = "{\"success\":0,\"msg\":\"用户名,不可以使用!\"}";
        }

        // 调用BaseAction中的方法向输出流中写JSON串
        responseWriterJSON(html);

    }

BaseAction代码:

package action;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;



public class BaseAction {

    public HttpServletResponse response;
    /**
     * 返回页面数据
     * @param returnString 返回数据
     * @throws IOException 异常
     */
    public void responseWriterJSON(String returnString) throws IOException  {
        
        response = ServletActionContext.getResponse();
        response.setContentType("application/json;charset=utf-8");
        
            response.getWriter().write(returnString);
            response.flushBuffer();
            response.getWriter().close();
         
    }
    /**
     * 返回页面xml数据
     * @param returnString 返回数据
     * @throws IOException  异常
     */
    public void responseWriterXML(String returnString) throws IOException  {
        
        response = ServletActionContext.getResponse();
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/xml");
        response.setHeader("Cache-Control", "no-cache");
        
            response.getWriter().write(returnString);
            response.flushBuffer();
            response.getWriter().close();
        
    }
    /**
     * 返回页面数据
     * @param returnString
     * @throws IOException  异常
     */
    public void printWriter(String returnString) throws IOException {
        
        response = ServletActionContext.getResponse();
        response.setContentType("text/html;charset=utf-8");
        
            PrintWriter out = response.getWriter();
            out.println(returnString);
            out.close();
        
    }
    
}

 

POST方式

js:

//-----------对用户名进行查询start-------------------------------------------
$(document).ready(function() {
    
        
        query();
    
});


//-----------对用户名进行查询end-------------------------------------------
//加载查询土地登记审批表(判断:add/update/search)
function query()
{  
    var username = "aa";
    var pwd = "bb";
    
    $.post(prjContextPath+"/updateAction!query.action",
    {username:username,pwd:pwd},callBackQuerySuccess);
}

function callBackQuerySuccess(json)
{   
    
    if(json.data != null || json.data !="")
    {
        //向页面赋值
        /*
         * 方法1
         for(var i=0;i<json.data.length;i++)
        {   var tbBody = "";
            var trColor="";
            alert("i="+i);
            var editData=json.data[i];
            
            if (i % 2 == 0) {
              trColor = "even";
            }
            else {
              trColor = "odd";
            }
            tbBody += "<tr class=‘" + trColor + "‘><td>" + editData.name + "</td>" + "<td>" + editData.age + "</td></tr>";
            $("#myTb").append(tbBody);

        }
        */
        
        
        //向页面赋值方法2
         var typeData = json.data;
          $.each(typeData, function(i, n) {
            var tbBody = ""
            var trColor;
            if (i % 2 == 0) {
              trColor = "even";
            }
            else {
              trColor = "odd";
            }
            tbBody += "<tr class=‘" + trColor + "‘><td>" + n.name + "</td>" + "<td>" + n.age + "</td>" + "<td>" + n.like[0] + "</td></tr>";
            $("#myTb").append(tbBody);
          });

        
    }
}

action:

package action;



import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import bean.User;
import bean.UserInfo;


import com.alibaba.fastjson.JSON;
import com.opensymphony.xwork2.ModelDriven;

public class UpdateAction extends BaseAction implements ModelDriven<User> {

    User user = new User();

    public User getModel() {
        return user;
    }

    public void query() throws IOException {

        System.out.println("username=" + user.getUsername());
        System.out.println("pwd=" + user.getPwd());
        
        
        UserInfo userinfo = new UserInfo();
        userinfo.setName("张三");
        userinfo.setAge(20);
        userinfo.setBirthday("1990-10-09");
        String[] likes = new String[] { "篮球", "足球" };
        userinfo.setLike(likes);
        userinfo.setHasgirlfirend(false);
        userinfo.setCar(null);
        
        UserInfo userinfo2 = new UserInfo();
        userinfo2.setName("李四");
        userinfo2.setAge(20);
        userinfo2.setBirthday("1991-11-11");
        String[] likes1 = new String[] { "台球", "羽毛球" };
        userinfo2.setLike(likes1);
        userinfo2.setHasgirlfirend(false);
        userinfo2.setCar(null);
        List<UserInfo> userJsonList = new ArrayList<UserInfo>();
        userJsonList.add(userinfo);
        userJsonList.add(userinfo2);

        String jsonArray = JSON.toJSONString(userJsonList);
        
        StringBuffer responseString = new StringBuffer();
        responseString.append("{\"total\":")
        .append(2)
        .append(",\"data\":")
        .append(jsonArray)
        .append("}");
        
        
        System.out.println(responseString.toString());

        // 调用BaseAction中的方法向输出流中写JSON串
        responseWriterJSON(responseString.toString());
       /**
       {
    "total": 2,
    "data": [{
        "age": 20,
        "birthday": "1990-10-09",
        "hasgirlfirend": false,
        "like": ["篮球", "足球"],
        "name": "张三1"
    }, {
        "age": 20,
        "birthday": "1990-10-09",
        "hasgirlfirend": false,
        "like": ["篮球", "足球"],
        "name": "张三"
    }]
    }
   */
        }

}

 

以上是关于jquery中ajax的使用(java)的主要内容,如果未能解决你的问题,请参考以下文章

jQuery高级Ajax

几个非常实用的JQuery代码片段

前端面试题之手写promise

使用 Jquery 的同步“Ajax”调用似乎不起作用

十条jQuery代码片段助力Web开发效率提升

十条jQuery代码片段助力Web开发效率提升