您的位置:首页 > Web前端 > JQuery

使用jQuery发送POST,Ajax请求返回JSON格式数据

2016-09-04 18:46 1691 查看
问题:
使用jQuery POST提交数据到PHP文件, PHP返回的json_encode后的数组数据,但jQuery接收到的数据不能解析为JSON对象,而是字符串{"code":-1,"msg":"123","data":[]}

jQuery get() 和 post() 方法用于通过 HTTP GET 或 POST 请求从服务器请求数据。

jQuery $.get() 方法
$.get() 方法通过 HTTP GET 请求从服务器上请求数据,在URL地址上可以看到传递的参数,一般用于传递少量数据。

语法: $.get(URL,callback);
详细语法:$(selector).get(url, data, success(response,status,xhr),dataType)

jQuery $.post() 方法
$.post() 方法通过 HTTP POST 请求从服务器上请求数据,在URL地址上不可以看到传递的参数,一般用于传递大量数据。

语法:$.post(URL,data,callback);
详细语法: jQuery.post(url,data,success(data, textStatus,jqXHR),dataType)

查看$.post()详细的语法:
jQuery.post(url,data,success(data, textStatus,jqXHR),dataType)
你会发现,最后边有个参数 dataType,这个就是问题所在。
这个dataType是可选参数,它规定预期的服务器响应的数据类型。默认执行智能判断(xml、json、script 或html)。

详细说明
该函数是简写的 Ajax 函数,等价于:
$.ajax({
  type: 'POST',
  url: url,
  data: data,
  success: success,
  dataType:
dataType

});

解决:

$.post() 加上最后边的一个可选参数 dataType 为“json”类型

示例:获得 test.php 页面返回的 json 格式的内容:
$.post("test.php", { "func": "getNameAndTime" },
   function(data){
    alert(data.name); // John
    console.log(data.time); // 2pm
   },
"json");

示例:获得 test.php 页面的内容,并存储为 XMLHttpResponse 对象,并通过 process() 这个JavaScript 函数进行处理:
$.post("test.php", { name: "John", time: "2pm" },
   function(data){
    process(data);
   },
"xml");

Struts2中对于后台向前端返回JSON格式数据一般使用以下方式:
<span style="font-size:18px;">	public void writeJson2Resp(String json) throws IOException {
HttpServletResponse resp = ServletActionContext.getResponse();
resp.setCharacterEncoding("gbk");
resp.setContentType("text/html;charset=gbk");  //这一句没加入会导致乱码
PrintWriter out = resp.getWriter();
out.write(json);
out.flush();
out.close();
}</span>


在 BaseAction 实现该方法,那么其他的 Action  只要继承了改类,就可以使用该方法向前台页面返回JSON格式数据

参考链接:
jQuery ajax 参考手册 http://www.w3school.com.cn/jquery/jquery_ref_ajax.asp
HTTP 方法:GET 对比 POST http://www.w3school.com.cn/tags/html_ref_httpmethods.asp
jQuery ajax - post() 方法: http://www.w3school.com.cn/jquery/ajax_post.asp
jQuery ajax - get() 方法 http://www.w3school.com.cn/jquery/ajax_get.asp
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  jquery ajax json