简体   繁体   中英

Accessing elements of returned JSON

I'm trying to access individual elements of my JSON that I've returned from a .post method with jQuery. When I send the data to create.php, all it does is json_encode the data and put it in a json object. Here is my code:

$.post("pages/create.php", {user : "user1", password : "pass2"}, function(data) {
    var newArray = new Array();
    newArray = {"user":"user2","password":"pass2"};
    console.log(newArray.user);
    console.log(data);
    console.log(data.user);

The issue is that the first two console logs do what I would expect. The first one gives me:

"user2"

The second gives me:

"user" : "user1", "password" : "pass2"

But the third is undefined, even though I know the data JSON object has stuff in it. Is my syntax wrong? I'm just trying to access a specific element of that JSON.

Add json as fourth parameter to the $.post() function as

$.post("pages/create.php", {user : "user1", password : "pass2"}, function( data ) {
    console.log( data.user);
}, "json");

This will post to the create.php page and get content which has been returned in json format.

And make sure create.php returns jsonencoded data as:

<?php echo json_encode(array("user1"=>"Kishor","pass1"=>"mypass")); ?>

Also set correct content type HTTP header for JSON as:

header('Content-Type: application/json');

Have a look at jQuery.post() and What is the correct JSON content type? .

给出的所有答案似乎都是正确的,我只是感觉你的JSON响应可能缺少“{”和“}”..但只是返回对象的属性...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM