JSON Post and Decode array to PHP


JSON Post and Decode array to PHP

我正在字符串中使用JSON将数组发布到PHP文件。它不起作用。问题是什么都没发生。如果我停用数据类型:"json",那么我会得到警报(但没有数据)。

这是我的jquery代码

var arr = new Array();
arr.push('1','Brussels|25');
arr.push('2','Antwerp|40');
$.ajax({
  type: "POST",
  contentType: "application/json; charset=utf-8",
  url: "jsondecode.php",
  data: JSON.stringify(arr),
  dataType: "json",
  success: function(data){alert(data);},
  failure: function(errMsg) {
    alert(errMsg);
  }
});

这是我的PHP代码(jsondecode.PHP);

 <?php
 $array = json_decode($_POST["arr"]);
 foreach($array as $el){
    $el_array=explode('|',$el);
    echo"City=".$el_array[0]." And Age = ".$el_array[1]."";
 }
 ?>

有人知道这方面有用的教程吗?

您必须以这种格式发布数据才能像$_POST["arr"] 一样检索

data: { arr : JSON.stringify(arr) },

你到底在干什么?看起来,您正试图将键值对放在具有arr.push('1', 'Brussels|25');的JavaScript数组中,在键"1"下需要一个包含"Brussels |25"的数组,但请注意,您正在创建此数组:["1", "Brussels|25", "2", "Antwerp|40"]

如果您想发送json,请发送json数据:

var arr= [{  
    "city" : "Brussels",  
    "age" : 25  
},{  
    "city" : "Antwerp",  
    "age" : 40  
}];  

然后您的ajax调用:

$.ajax({
   type: "POST",
   url: "jsondecode.php",
   data: {arr: JSON.stringify(arr)},
   success: function(data){
        console.log("success:",data);},
   failure: function(errMsg) {
        console.error("error:",errMsg);
   }
});

因此,您不需要在数据服务器端进行分解。

服务器端脚本:

<?php
$data = json_decode($_POST["arr"]);
// will echo the JSON.stringified - string:
echo $_POST["arr"];
// will echo the json_decode'd object
var_dump($data);
//traversing the whole object and accessing properties:
foreach($data as $cityObject){
    echo "City: " . $cityObject->city . ", Age: " . $cityObject->age . "<br/>";
}
?>

希望,这对你有帮助。

@edit:顺便说一下,使用console.log()console.error()而不是alert。警报将导致脚本暂停,直到您单击"确定",并且您无法在警报中看到对象。

@第二次编辑:脚本现在已经测试完毕,我删除了不必要的代码,并添加了服务器端代码

替换:

$array = json_decode($_POST["arr"]);

签字人:

 $array = json_decode($_POST["arr"], true);

为我工作:

JS:

$.ajax({
    type: "POST",
    contentType: "application/json; charset=utf-8",
    url: "jsondecode.php",
    data: JSON.stringify({"1": "Brussels", "2": "Antwerp"}),
    success: function(data){alert(data);},
    failure: function(errMsg) {
        alert(errMsg);
    }
});

PHP:

<?php
$p = file_get_contents('php://input');
$x = json_decode($p, true);
echo $x["1"];
?>