简体   繁体   中英

How to access JSON object property from data returned by AJAX call?

I'm making an AJAX call to this php file:

<?php 
    $result = array('error' => "Please enter a valid name");
    echo  json_encode($result)
?>

In my javascript file, I have:

$.ajax({
    type:"POST",
    url:"/controller/common/review_processing.php", 
    data:dataString, 
    success:function (data) {
        var returned_data = data;
        console.log(returned_data); <---This outputs {"error":"Please enter a valid name"} 
        console.log(returned_data.error); <---This outputs undefined
    }

});

My data seems to be encoded as a JSON object correctly but when I try to access a specific property, I get an undefined result.

What I want is for console.log(returned_data.error) to output:

Please enter a valid name

What am I doing wrong?

Please try :

$.ajax({
    type:"POST",
    url:"/controller/common/review_processing.php", 
    data:dataString,
    dataType: "json", <--response itself will be handled as JSON
    success:function (data) {
        var returned_data = data;
        console.log(returned_data); <---This outputs {"error":"Please enter a valid name"} 
        console.log(returned_data.error); 
    }

});

Try using this...

$.map(data.d, function (item) {
  console.log(item.error);
});

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