[英]php, ajax and json encoding/decoding
I'm using jQuery and jquery-json to post data to a PHP script. 我正在使用jQuery和jquery-json将数据发布到PHP脚本。
$.post('<?php echo url_for('/ajax.php'); ?>', 'data=' + $.toJSON(order), function (response) {
if (response == "success") {
$("#respond").html('<div class="success">Item Saved!</div>').hide().fadeIn(1000);
setTimeout(function () {
$('#respond').fadeOut(1000);
}, 2000);
}
})
If I console.log(order) I get the following JOSN: 如果我console.log(order)我得到以下JOSN:
{"details":[{"template_id":"25","font_size":"22"}]}
In my ajax.php file I have: 在我的ajax.php文件中,我有:
$data = json_decode($_POST["data"]);
var_dump($data);exit;
Which returns 'NULL' 返回“ NULL”
But when I have the following code: 但是当我有以下代码时:
$data = $_POST["data"];
var_dump($data);exit;
It returns: 它返回:
string(61) "{\"details\":[{\"template_id\":\"25\",\"font_size\":\"26\"}]}"
Is there any reason why it is escaped? 有什么理由可以逃脱吗?
What is the easiest way to decode this? 最简单的解码方法是什么?
Thanks 谢谢
you may need to disable magic_quotes_gpc
in your php.ini or .htaccess file which is adding the slashes to your post variables. 您可能需要禁用php.ini或.htaccess文件中的
magic_quotes_gpc
,该文件会将斜杠添加到post变量中。
Or you could just call stripslashes
on $_POST['data'] like so: 或者,您可以像这样在$ _POST ['data']上调用
stripslashes
:
$data = json_decode(stripslashes($_POST["data"]));
You need to add dataType: 'json' to your ajax call. 您需要将dataType:'json'添加到您的Ajax调用中。
$.ajax({
url: url,
type: 'post',
dataType: 'json',
data: $.toJSON(order),
async: true,
success: function (data) {
if (data.response) {
$("#respond").html('<div class="success">Item Saved </div>').hide().fadeIn(1000);
setTimeout(function () {
$('#respond').fadeOut(1000);
}, 2000);
}
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.