JS对象->;来自jquery ajax的JSON提交->;php迭代


JS object -> JSON submission from jquery ajax -> php iteration

我正在构建一个流程,在这个流程中,js对象通过ajax(POST和json类型)提交到php文件,而我在迭代php中提交的内容时遇到了问题。

我的对象看起来像这样:

var myObject = {
  "section1":{
  "subitem1":"value1",
  "subitem2":"value2"
 },
  "section2":{
  "subitem3":"value3",
  "subitem4":"value4"
 }
}

我的ajax看起来是这样的:

$.ajax({
url:"test.php?section=section2",
type:"POST",
dataType:"json",
success:function(data){
// what i do with the response data
},
data:myObject
});

这是我的php:

$section = $_GET['section'];
$json = json_decode($_POST[$section], true);
foreach($json as $key=>$value){
   //if this iteration works here, it'll be the happiest point of my day
}

现在,在上面的php中,如果我将某个部分称为$_POST['section2'],那么迭代确实有效。因此,使用PHP的变量变量似乎是个问题,但我不知道。。。。整个$_POST似乎也是作为一个对象出现的。JQUERY AJAX会自动对我提交的对象执行JSON.stringify吗?我试过用stringify,但没用。。我有最新版本的chrome。。。

此外,我还尝试在$_POST上使用json_decode。。。仍然$_POST[$section]被解释为null。。。

非常感谢任何帮助、建议和建议!!

这不是你想的那样,字符串化对象并将其作为键/值对的一部分发送,然后从post字段对其进行解码。

$.ajax({
    url:"test.php?section=section2",
    type:"POST",
    dataType:"json",
    success:function(data){
    // what i do with the response data
    },
    data:{json:JSON.stringify(myObject)}
});    
$section = $_GET['section'];
$json = json_decode($_POST['json']);
$current_section = $json->{$section};
foreach($current_section as $key=>$value){
   //if this iteration works here, it'll be the happiest point of my day
}

假设$_POST数组只有一个值——对象——试试这个:

$section = $_GET['section'];
$tmpArray = json_decode(array_pop($_POST), true);
$json = $tmpArray[$section];