PHP - How to read message data without a key?

This piece of jQuery codes is sent to one of our php pages.

var json = '{"object1":{"object2":[{"string1":val1,"string2":val2}]}}';
$.post("phppage", json, function(data) {
    alert(data);
});

Inside phppage, I need to do some processing depending on the message data. But I can not read these messages.

foreach ($_POST as $k => $v) {
    echo ' Key= ' . $k . ' Value= ' . $v;
}
+3
source share
3 answers

What you need should work fine, but the JSON object turns into an array of arrays when it is provided to the given POST. 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 contains all the other data. If you do

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

"object1 > Array". , . , , , , , .

+3

file_get_contents("php://input") , script, key=value . API- jsonrpc.

+3

Step 1 (Javascript Code):

Instead:

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

Do 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
source

Source: https://habr.com/ru/post/1768814/


All Articles