php - JS 对象 -> 从 jquery ajax 提交 JSON -> php 迭代

标签 php javascript json object casting

我正在构建一个流程,其中 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
}

关于php - JS 对象 -> 从 jquery ajax 提交 JSON -> php 迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12168655/

相关文章:

php - 使用 nusoap 通过 Web 服务从 Sharepoint 库下载文件

php - 有没有办法用 PHP 编写 android 应用程序?

php - 文件上传和安全问题

PHP 只删除数字

php - 不明确的查询 [codeigniter]

javascript - 单击按钮时验证 html 表单

javascript - 如何使用正则表达式从字符串中提取 block 注释?

json - Swift 将创建的结构实例返回给函数

javascript - 根据特定键值对 JavaScript 对象重新排序

json - Hive Metastore 列宽限制