用json响应jQuery ajax请求,怎么样?

我发送一个带有2个post值的ajax请求,第一个是“action”,它定义了我的php脚本要解析的操作,另一个是“id”,它是用来解析脚本的用户的id。
服务器在array()中返回6个值,然后使用PHP函数编码为JSON: json_encode();
我的一些回复是HTML,但当我将其编码为JSON时,它会转义为"/"因此它变为"\/"
我该如何禁用它?

当我得到服务器响应时,当我不知道如何在jQuery中显示它时,我只是认为将它全部放入div只会显示我请求的数字和HTML代码,但它显示数组,因为它是用PHP编码。

PHP

 $response = array(); $response[] = "link"; $response[] = 1; echo json_encode($response); 

jQuery的:

 $.ajax({ type: "POST", dataType: "json", url: "main.php", data: "action=loadall&id=" + id, complete: function(data) { $('#main').html(data.responseText); } }); 

如何使这个工作JSON?

你需要打电话给

 $.parseJSON(); 

例如:

 ... success: function(data){ var json = $.parseJSON(data); // create an object with the key of the array alert(json.html); // where html is the key of array that you want, $response['html'] = "something.."; }, error: function(data){ var json = $.parseJSON(data); alert(json.error); } ... 

在http://api.jquery.com/jQuery.parseJSON/中看到这个

如果你仍然有斜杠的问题:搜索security.magicquotes.disabling.php或: function.stripslashes.php

注意:

这里的答案是那些尝试使用$.ajax并将dataType属性设置为json ,甚至是错误的响应类型的人。 定义header('Content-type: application/json'); 在服务器中可能会纠正问题,但如果您要返回text/html或任何其他类型, $.ajax方法应将其转换为json 。 我使用旧版本的jQuery进行测试,并且仅在版本1.4.4使用$.ajax强制将任何内容类型转换为传递的dataType 。 因此,如果您遇到此问题,请尝试更新您的jQuery版本。

首先,如果您将PHP的标头设置为提供JSON,它将有所帮助:

 header('Content-type: application/json'); 

其次,它将有助于调整您的ajax调用:

 $.ajax({ url: "main.php", type: "POST", dataType: "json", data: {"action": "loadall", "id": id}, success: function(data){ console.log(data); }, error: function(error){ console.log("Error:"); console.log(error); } }); 

如果成功,您收到的响应应该被选为真正的JSON,并且应该将对象记录到控制台。

注意:如果你想获取纯HTML,你可能想考虑使用另一种方法来使用JSON,但我个人建议使用JSON并使用模板(例如Handlebars js )将其渲染为html。

使用带有绑定数据的发送和接收操作码连接您的javascript客户端控制器和php服务器端控制器。 所以你的php代码可以作为js recepient / listener的响应函数delta发送

请参阅https://github.com/ArtNazarov/LazyJs

对不起,我的英语不好

由于您将标记创建为字符串,因此您无法将其转换为json。 只需发送它,因为它使用implode方法组合所有数组元素。 试试这个。

PHP改变

 $response = array(); $response[] = "link"; $response[] = 1; echo implode("", $response);//<-----Combine array items into single string 

JS(将数据类型从json更改为html或者只是不设置它jQuery会搞清楚)

 $.ajax({ type: "POST", dataType: "html", url: "main.php", data: "action=loadall&id=" + id, success: function(response){ $('#main').html(response); } });