我正在尝试解码我在 javascript (jquery) 中使用 ajax 调用发送的 php 中的 JSON。
JavaScript 代码:
var editSchedule_data = {
'action' : 'editSchedule',
'eventid' : $('#eventid').val(),
'pixels_per_minute' :$('#pixels_per_minute').val(),
artists: {
artist: []
}
}
$('.artist').each(function(index) {
var id=$(this).attr('id');
id=id.split('_');
editSchedule_data.artists.artist.push({
'artistid' : id[0],
'stageid' : id[1],
'left' : $(this).offset().left-$('.artists').offset().left,
'width' : $(this).width()
});
});
$.ajax({
type : "POST",
url : "callback.php",
data : editSchedule_data,
dataType : "json",
async : true,
success : function(json) {
if(json.success) {
showSucces(json.message);
}
else{
showError(json.message);
}
},
error: function(error){
alert("An error occurred: "+error.message);
}
});
PHP 代码:
$clean = sanitize($_POST);
echo(json_encode($clean['artists']),
json_last_error());
echo(json_decode($clean['artists']),
json_last_error());
我的输出: 编码:
{"artist":[{"artistid":"4","stageid":"3","left":"360","width":"240"},{"artistid":"3","stageid":"4","left":"120","width":"240"},{"artistid":"1","stageid":"5","left":"120","width":"180"},{"artistid":"2","stageid":"5","left":"300","width":"120"},{"artistid":"5","stageid":"6","left":"480","width":"120"}]}
0
解码:
0
谁能告诉我如何使解码功能正常工作?
最佳答案
你为什么要在那里使用 json_decode?您已经在 $_POST 中将数据作为数组。这就是为什么 json_decode 失败并返回 NULL 的原因……它需要一个格式正确的字符串,而您正在向它传递一个数组。 如果 dataType : "json"参数让您感到困惑,它指定您期望从服务器返回的数据类型,而不是您发送的数据类型。 您应该简单地处理来自 $_POST 的数据,创建您的响应,对其应用 json_encode 并回显结果字符串。
关于php - PHP中的Json解码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4041221/