简体   繁体   中英

AJAX response, cant alert JSON String properly

Im finding a strange problem.

Using php i am running a select query on mysql database, i am trying to return this to my ajax call so i can for loop through it, but i always get undefined as an alert, i can alert the whole json string however, but cant target values.

Ajax code:

        $.ajax({
            type: "POST",
            url: 'database_data.php',
            data: {
                action: 'ct',
                input: input
            },
            success: function (data) {
                var obj = JSON.parse(data);
                alert(obj[0].pid);
                alert(data[0].pid);
            },error: function(request, status, error){
                alert("Error: Could not delete");
            }
        });

PHP Code:

$base= mysqli_connect($dbhost,  $dbuser, $dbpass, $dbbase);
if ($_POST['action']== "ct"){
  $input = $_POST['input'];
  $return_arr = array();
  $sql = "SELECT pid FROM programmes WHERE complete_title LIKE '%$input%' LIMIT 30";

if ($result = mysqli_query( $base, $sql )){
    while ($row = mysqli_fetch_assoc($result)) {
        $row_array['pid'] = $row['pid'];
        array_push($return_arr,$row_array);
    }
}

mysqli_close($base);

echo json_encode($return_arr);

}

Alerting data gives a response as so:

[{"pid":"p00547jm"},{"pid":"p0054880"},{"pid":"p005492h"},...

If i chose to alert data[0], data[1] it prints each individual character

You can use dataType to tell jquery what you are expecting back from the server. See http://api.jquery.com/jquery.ajax/

In your case

   $.ajax({
            type: "POST",
            url: 'database_data.php',
            dataType: 'json',
            data: {
                action: 'ct',
                input: input
            },
            success: function (data) {
                var obj = data; // I should already be json!
                alert(obj.pid);
                alert(data.pid);
            },error: function(request, status, error){
                alert("Error: Could not delete");
            }
        });

This is because you are probably getting string as a response. So your data is a string .

You can use JSON.parse() to parse it into JSON object and the access the data like this,

 data = '[{"pid":"p00547jm"},{"pid":"p0054880"},{"pid":"p005492h"}]'; console.log(JSON.parse(data)[0].pid); 

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