Fla*_*ing 35 php ajax jquery json
我发送一个带有2个post值的ajax请求,第一个是"action",它定义了我的php脚本要解析的操作,另一个是"id",它是用来解析脚本的用户的id.
服务器在array()中返回6个值,然后使用PHP函数编码为JSON:json_encode();
我的一些响应是HTML,但是当我将它编码为JSON时,它会逃脱,"/"所以它变成了"\/"
如何禁用它?
当我得到服务器响应时我不知道如何在jQuery中显示它,我只是认为将它全部放入div只会显示我请求的数字和HTML代码,但它显示数组,因为它是用PHP编码.
PHP
$response = array();
$response[] = "<a href=''>link</a>";
$response[] = 1;
echo json_encode($response);
Run Code Online (Sandbox Code Playgroud)
jQuery的:
$.ajax({
type: "POST",
dataType: "json",
url: "main.php",
data: "action=loadall&id=" + id,
complete: function(data) {
$('#main').html(data.responseText);
}
});
Run Code Online (Sandbox Code Playgroud)
如何使这个工作JSON?
Gui*_*rme 49
你需要打电话给
$.parseJSON();
Run Code Online (Sandbox Code Playgroud)
例如:
...
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'] = "<a>something..</a>";
},
error: function(data){
var json = $.parseJSON(data);
alert(json.error);
} ...
Run Code Online (Sandbox Code Playgroud)
在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版本.
sgb*_*sgb 29
首先,如果您将PHP的标头设置为提供JSON,它将有所帮助:
header('Content-type: application/json');
Run Code Online (Sandbox Code Playgroud)
其次,它将有助于调整您的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);
}
});
Run Code Online (Sandbox Code Playgroud)
如果成功,您收到的响应应该被选为真正的JSON,并且应该将对象记录到控制台.
注意:如果你想获取纯HTML,你可能想考虑使用另一种方法来使用JSON,但我个人建议使用JSON并使用模板(例如Handlebars js)将其渲染为html .