JSON object via jQuery post to php

2020-07-17 05:25发布

I know, there are plenty of questions out there, but none of them worked for me.

I build an array with normal javascript objects in javascript and sent it via jquery.post to the server. However on the server, I can't access the data using php $obj->value . I tried json_decode/encode and so on.

This is what console.log(data) gives me, before sending it to the server.

enter image description here

Than on the php part I only do this:

 $data= $_POST['data'];
 print_r($data);

The output of print_r is:

enter image description here

And thats how my Jquery post looks like:

    $.post("programm_eintragen.php",{
            data: data,

        }).success(
            function(data){                 
                    //success

        }).error(
            function(){
            console.log("Error post ajax " );
        },'json');      

Could somebody tell me:

how I can access my object properties on the php site properly?

I also get tried to access non object .... or php interprets the json object as a string an data[0] returns me [.

I thought, I could do it like this:

$data[0]->uebungen[0] 

Am I just being silly and missing something?

Why is this whole json sending to php thing such a problem?

2条回答
虎瘦雄心在
2楼-- · 2020-07-17 05:46

In JavaScript, your're not actually sending a JSON encoded string, your are just sending form data. To actually send a JSON string, you need to convert it (the object) to a string.

$.post("programm_eintragen.php",{
  data: JSON.stringify(data),
});

On the receiving side (php script) you will have a JSON string. You can decode it.

$data = json_decode($_POST['data'], true);

var_dump($data[0]['uebungen'][0]);

However, these steps are not necessary. All the json_encoding can be avoided by just accessing the array directly. For this example, ignore the above javascript, and don't change anything in your code.

$data = $_POST['data'];
var_dump($data[0]['uebungen'][0]);

example

查看更多
该账号已被封号
3楼-- · 2020-07-17 06:03

This is how I do it:

JavaScript

var data_obj = {
    "function": "create_customer",
};
$.post({ url: "src/index.php", dataType: "json", data: data_obj }, function (data) {

});

PHP

$json_obj = json_decode(json_encode($_POST));
$function = $json_obj->{"function"};

URL is the path relative to index.html.

查看更多
登录 后发表回答