0

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として解釈されます...

どんな助け、提案、アドバイスも大歓迎です!

4

2 に答える 2

2

それはあなたが思っていることにはなりません。オブジェクトを文字列化し、キーと値のペアの一部として送信してから、投稿フィールドからデコードします。

$.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
}
于 2012-08-28T23:06:26.927 に答える
0

$ _POST配列に1つの値(オブジェクト)しかない場合は、次のことを試してください。

$section = $_GET['section'];
$tmpArray = json_decode(array_pop($_POST), true);
$json = $tmpArray[$section];
于 2012-08-28T23:01:54.613 に答える