jQuery POST提交数据返回的数据不能解析为JSON对象

2023-05-16

jQuery POST提交数据返回的数据不能解析为JSON对象

问题:

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

分析:

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

jQuery $.get()方法

$.get() 方法通过 HTTP GET 请求从服务器上请求数据。
语法:$.get(URL,callback);
详细语法:

$(selector).get(url, data, success(response,status,xhr), dataType)

jQuery $.post() 方法

. p o s t ( ) 方 法 通 过 H T T P ‘ P O S T ‘ 请 求 从 服 务 器 上 请 求 数 据 。 语 法 : .post() 方法通过 HTTP `POST` 请求从服务器上请求数据。 语法: .post()HTTPPOST.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");

参考链接:

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

原文地址:
http://blog.sina.com.cn/s/blog_6c971aa30102vkaw.html

[END]

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

jQuery POST提交数据返回的数据不能解析为JSON对象 的相关文章

随机推荐