开发者

PHP - How to read post data with no key?

开发者 https://www.devze.com 2023-01-19 14:50 出处:网络
This piece of jQuery code posts to one of our php pages. var json = \'{\"object1\":{\"object2\":[{开发者_如何学JAVA\"string1\":val1,\"string2\":val2}]}}\';

This piece of jQuery code posts to one of our php pages.

var json = '{"object1":{"object2":[{开发者_如何学JAVA"string1":val1,"string2":val2}]}}';
$.post("phppage", json, function(data) {
    alert(data);
});

Inside phppage, I have to do some processing depending on the post data. But I am not able to read the post data.

foreach ($_POST as $k => $v) {
    echo ' Key= ' . $k . ' Value= ' . $v;
}


use file_get_contents("php://input") to capture the data received by your script when key=value pairs are not used. This approach is common with jsonrpc APIs.


What you have should work fine, but the JSON object is turned into an array of arrays when it is given to the POST data. You will get something like this:

["object1"]=>
  array(1) {
    ["object2"]=>
    array(1) {
      [0]=>
      array(2) {
        ["string1"]=>
        string(4) "val1"
        ["string2"]=>
        string(4) "val2"
      }
    }
  }
}

So object1 is an array that holds all the other data. If you do

foreach ($_POST as $key => $val) {
   echo $key . " > " . $val
}

It prints out "object1 > Array". In other words you need to iterate through the value as well. How you do this depends on how the data you are receiving is structured or whether you even know how it is structured.


Step 1 (Javascript code):

Instead of:

$.post("phppage", json, function(data) {
    alert(data);
});

Make it:

$.post("phppage", 'json':json, function(data) {
    alert(data);
});

Step 2 (PHP code):

Change to:

$json=json_decode($_POST['json']);
foreach($json as $k => $v) {
  echo ' Key= ' . $k . ' Value= ' . $v;
}

or:

$json=json_decode($_POST['json']);
print_r($json);
0

精彩评论

暂无评论...
验证码 换一张
取 消