使用jQuery更新JSON&;PHP-json_decode()返回空
我正试图将json发布到txt文件,但我的数据有一些问题。每当我检查要在jQuery中发送的数据时,一切看起来都很好,但如果我用php打印出来,我会看到转义斜杠,json_decode会将该数据返回为空。以下是代码片段: jQuery使用jQuery更新JSON&;PHP-json_decode()返回空,php,jquery,ajax,json,Php,Jquery,Ajax,Json,我正试图将json发布到txt文件,但我的数据有一些问题。每当我检查要在jQuery中发送的数据时,一切看起来都很好,但如果我用php打印出来,我会看到转义斜杠,json_decode会将该数据返回为空。以下是代码片段: jQuery $.ajax({ type : 'POST', url : 'update-json.php', dataType : 'json', data : {json : JSON.stringify([{'name':'Bob'},{'
$.ajax({
type : 'POST',
url : 'update-json.php',
dataType : 'json',
data : {json : JSON.stringify([{'name':'Bob'},{'name':'Tom'}])},
success : function(){
console.log('success');
},
error : function(){
console.log('error');
}
});
PHP
<?php
$json = $_POST['json'];
$entries = json_decode($json);
$file = fopen('data-out.txt','w');
fwrite($file, $entries);
fclose($file);
?>
PHP ECHO$entries
//EMPTY
看起来您在PHP中启用了magic_引号。一般来说,您应该关闭此功能以避免出现类似的问题。如果不能这样做,则需要对传入字符串调用
stripslashes()
您还可以检查json\u last\u error()
,找出它无法解码的原因
编辑:下面是您如何输入stripslashes
$json = stripslashes($_POST['json']);
$entries = json_decode($json);
if( !$entries ) {
$error = json_last_error();
// check the manual to match up the error to one of the constants
}
else {
$file = fopen('data-out.txt','w');
fwrite($file, $json);
fclose($file);
}
从
json\u decode()
的文档中,如果无法解码json,则返回NULL
。是-我假设由于添加了额外的斜杠,因此无法解码。我想真正的问题是如何修复这些引号代码>但它将[{\'name\':\'Bob\'},{\'name\':\'Tom\'}]
写入txt文件。有没有办法不显示这些斜杠?在调用json\u decode
之前,需要调用stripslashes
。该代码调用json\u decode
firstThank-我尝试过,但现在它只是将Array
写入文件。我没有注意到您将$json
打印到文件中,而不是$entries
(在上面的代码中)。这是你的意图吗?如果您只是将$entries
写入文件,我希望它会显示Array。您试图实现的最终结果是什么?您还可以通过执行print\r($entries)
$json = stripslashes($_POST['json']);
$entries = json_decode($json);
if( !$entries ) {
$error = json_last_error();
// check the manual to match up the error to one of the constants
}
else {
$file = fopen('data-out.txt','w');
fwrite($file, $json);
fclose($file);
}