jQuery使用ajax传递json数组
我有一个处理数组的ajax请求(我修剪了脚本以便集中精力处理正确的部分) 我的ajax:jQuery使用ajax传递json数组,jquery,arrays,ajax,Jquery,Arrays,Ajax,我有一个处理数组的ajax请求(我修剪了脚本以便集中精力处理正确的部分) 我的ajax: $.ajax({ type: "POST", url: "test.php", data: { 'usertrips': JSON.stringify(usertrips) }, dataType: "json", success: function(response){
$.ajax({
type: "POST",
url: "test.php",
data: {
'usertrips': JSON.stringify(usertrips)
},
dataType: "json",
success: function(response){
$('#alerts').html('<div class="success">OK</div>');
},
error: function(){
$('#alerts').html('<div class="error">NOT OK</div>');
}
});
所以发生了一些奇怪的事情。在我插入有争议的代码之前,脚本一直在正常工作。当我签入控制台数组返回时,没有错误。jQuery移动到代码的错误部分
有什么建议吗?我做错了什么?非常感谢。ajax:
$strRequest = file_get_contents('php://input');
$Request = json_decode($strRequest);
$.ajax({
类型:“POST”,
url:“test.php”,
数据:{
'usertrips':JSON.stringify(usertrips)
},
数据类型:“json”,
成功:功能(响应){
$('#alerts').html('OK');
$(“#results”).html(response.usertrips);
},
错误:函数(){
$('#警报').html('不正常');
}
});
php:
$data=json\u decode($\u POST['usertrips']);
foreach($数据作为$项){
$response['usertrips']。=“$item ”;
///将每个项目插入mysql
}
echo json_编码($response);
您已经告诉jQuery通过数据类型“JSON”期待JSON响应。
。在foreach
循环中使用echo$item
几乎可以保证您的响应不会是JSON。jQuery在错误回调中提供信息。你为什么不使用它呢,例如error:function(qXHR,textStatus,errorshown){…}
是的,你是对的…使用了$response['usertrips']。=“$item
”;谢谢你向我指出这一点。顺便说一句,这是一个学习的过程,有时我们只是看不见东西,或者没有正确地理解它们。我花了足够的时间来解决这个问题,菲尔很快就让我走上了正轨。你是说你的问题解决了吗?你知道为什么要使用数据类型:“json”
?如果没有,那么您应该做的第一件事就是查看您正在使用的代码的文档,特别是如果您不知道为什么要使用iti,那么我希望json_decode来完成这项工作。显然不起作用,我用工作代码发布了答案。感谢Phil.OP在应用程序/x-www-form-urlencoded
请求负载中为“usertrips”属性发布了一个JSON字符串<代码>php://input
将不是JSON字符串
$strRequest = file_get_contents('php://input');
$Request = json_decode($strRequest);
$.ajax({
type: "POST",
url: "test.php",
data: {
'usertrips': JSON.stringify(usertrips)
},
dataType: "json",
success: function(response){
$('#alerts').html('<div class="success">OK</div>');
$("#results").html(response.usertrips);
},
error: function(){
$('#alerts').html('<div class="error">NOT OK</div>');
}
});
$data = json_decode($_POST['usertrips']);
foreach($data as $item){
$response['usertrips'] .= "<li>$item<li>";
/// insert each item to mysql
}
echo json_encode($response);