AJAX回调(调用后台方法返回数据)

记得先要导入jquery.js。

格式一 $.ajax({"Key1":"value1","key2":"value2",....});

$.ajax({

  type:"post/get",

     asynch : “false”,//并发访问时异步提交

  url:"TestAction!execute?time="+Math.random(), 

  dataType:"json",//指定返回格式,不指定则返回字符串

  data:{"id":1,"name":"张三"},

  success:function(data){
    alert("返回结果集="+data);

  }

});

 

格式二 $.get/post(url,data,callback);

$(function(){

  $.get(

    "TestAction!execute?time="+Math.random(),

    {"id":1,"name":"张三"},

    function(data){

     alert("返回结果集="+data);

    }

  );

});

 

格式三 $.getJSON(url,data,callback);

$(function(){

  $.getJSON( 

    "TestAction!execute?time="+Math.random(),

    {"id":1,"name":"张三"},

    function(data){

     alert(data.name);//返回JSON格式

    }

  );

});

 

 

//后台代码

public String savePrivilege(){
PrintWriter out=null;
Long msg=null;
try {
out=getResponse().getWriter();
msg=request.getParameter("id")+request.getParameter("name");
} catch (Exception e) {
e.printStackTrace();
}
out.print(msg);
out.close();
return null;
}

//JSON格式

public String queryChildNode(){
User user=new User(getRequest().getParameter("id"),request.getParameter("name");
JSONObject json=JSONObject.fromObject(list);
getResponse().setContentType("text/html;charset=utf-8");
PrintWriter out=null;
try {
out = getResponse().getWriter();
} catch (IOException e) {
e.printStackTrace();
}
out.print(json.toString());
out.close();
return null;
}

 

 

 

posted @ 2014-03-22 00:07  莫名字  阅读(16882)  评论(0编辑  收藏  举报