无法将JSON发送到服务器

时间:2012-06-18 19:39:07

标签: jquery json post

我无法让服务器识别JSON POST请求,因为我稍微更改了代码。以前,对于for循环的每次迭代都会发出POST请求,但现在我已将其更改为包含多级JSON数组。

var json=[];

for (var i=0; i < tourList.length; i++){
  var data = tourList[i];
  json.push({latitude: data.position.ab, longitude: data.position.cb, filename: data.title, stopNum: i});
}

var results= JSON.stringify(json);
console.log(json);
console.log(results);

//this code was previously inside the for loop above, moved it outside
$.ajax({
  type: "POST",
  url: "../includes/phpscripts.php?action=postTour",
  data: results,
  datatype: "json",
  beforeSend: function(x){
    if (x && x.overrideMimeType){
      x.overrideMimeType("application/json;charset=UTF-8");
    }
  },
  success: function(data){
    if (data == "success")
      console.log("Tour update successful");
    else 
      console.log("Tour update failed");
  }
});

此时,tourList的长度为6,results基于Google Maps标记点击,并在Firebug中生成:

[
  {"latitude":43.682211,"longitude":-70.45070499999997,"filename":"../panos/photos/1-prefix_blended_fused.jpg","stopNum":0},
  {"latitude":43.6822,"longitude":-70.45076899999998,"filename":"../panos/photos/2-prefix_blended_fused.jpg","stopNum":1},
  {"latitude":43.682219,"longitude":-70.450828,"filename":"../panos/photos/3-prefix_blended_fused.jpg","stopNum":2},
  {"latitude":43.68218,"longitude":-70.45088699999997,"filename":"../panos/photos/4-prefix_blended_fused.jpg","stopNum":3}
]

但是,没有任何内容显示为$_POST变量,因为$_POST在调试器中显示为type: array[0]。所以我没有数据集来运行json_decode。从我所看到的,JSON是有效的。有什么问题?

2 个答案:

答案 0 :(得分:4)

您没有发送键/值,只有值

在ajax改为:

 data: {results:results},

在php中

$results=$_POST['results']

现在您可以使用json_deocde($results)

答案 1 :(得分:2)

将字符串作为post var。

发送
$.ajax({
  type: "POST",
  url: "../includes/phpscripts.php?action=postTour",
  data: {"json": results},
  dataType: "json",
  beforeSend: function(x){
    if (x && x.overrideMimeType){
      x.overrideMimeType("application/json;charset=UTF-8");
    }
  },
  success: function(data){
    if (data == "success")
      console.log("Tour update successful");
    else 
      console.log("Tour update failed");
  }
});

使用$_POST["json"]

访问json

我不确定你从PHP返回什么,但是,如果它是json,它永远不会等于"success"

编辑:还有一个问题。您的datatype参数应为dataType,此参数仅定义从PHP返回的dataType,而不是您发送的内容。