【问题标题】:JS object -> JSON submission from jquery ajax -> php iterationJS 对象 -> 来自 jquery ajax 的 JSON 提交 -> php 迭代
【发布时间】:2012-08-23 12:22:28
【问题描述】:

我正在构建一个进程,其中 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 的 variables 变量似乎是个问题,但我不知道....整个 $_POST 似乎也作为一个对象出现。 JQUERY AJAX 会自动对我提交的对象执行 JSON.stringify 吗?我试过使用 stringify 但它没有用..我有最新版本的 chrome...

另外,我也尝试在 $_POST 上使用 json_decode...仍然 $_POST[$section] 被解释为 null...

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

【问题讨论】:

  • 您能否对 $_POST 数组进行 var_dump 以便我们查看它是如何接收数据的?

标签: php javascript json object casting


【解决方案1】:

这与您的想法不同,将对象字符串化并将其作为键/值对的一部分发送,然后从 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 时将其转换为 json 是这种情况,我不应该使用 JSON.stringify(myObject) 而不是 $.parseJSON(myObject) 吗? $.parseJSON(myObject) 不是用 json 来创建对象的吗?
  • 我的另一个问题是迭代通过 ajax 提交的内容的标准/最佳实践方式是什么?是否将传入变量(POST 或 GET)视为多维数组或对象?非常感谢您的帮助。
  • @StillQuestioning 你是对的,我修好了。 $_GET 或 $_POST 中的数据始终是字符串或字符串数​​组(如果名称末尾有 [],它将是数组的一部分),开发人员应该知道会发生什么,如果他们不知道的话有事吗。阅读更多php.net/manual/en/language.variables.external.php
  • 我已按照您的指示确保并确认 php 接收字符串中的 json 并成功使用 json_decode() 获取对象或关联数组。但是,我仍然遇到使用变量动态引用特定子对象/数组的问题。本质上,$current_section = $json->{$section}; 不适合我。奇怪的是,如果我手动执行$current_section = $json->{"section2"}; 它确实可以工作...但我的应用程序必须动态引用此元素...有什么想法吗??帮助..谢谢..
  • @StillQuestioning json_decode 的第二个参数错误并返回数组,我将其删除,因此它返回一个对象。我测试了它,它对我有用。
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-05
    • 2016-10-31
    • 2015-06-04
    • 1970-01-01
    • 2011-09-12
    • 1970-01-01
    • 2010-10-02
    • 1970-01-01
    相关资源
    最近更新 更多