简体   繁体   中英

How can I return an array object to a jquery $.ajax call?

I am trying to return an array object to my Jquery ajax call, but it seems to return as a String with Array length =1

PHP code:

$results = mysqli_query($link, $sql);

if ($results->num_rows > 0) {

    while ($row = $results->fetch_assoc()) {


        $array = array($row['eventDate'], $row['time'] ,['data' => $row['time']])   ;

        echo json_encode($array) ;
    }
} else {
    echo "0 results";
}

Response in Developer tools shows:

["12_03_2015","0:00:00",{"data":"0:00:00"}]["12_03_2015","0:00:00",{"data":"0:00:00"}]["12_03_2015","0:00:00",{"data":"0:00:00"}]

My Ajax Call:

function trend(data){

$.ajax({
    url: "trendData.php",
    cache: true,
    type: "POST",
    data: {arr:data},

    success: function (data) {
        originalData=[];

        originalData.push(data)
        trender(data)
    }
});

}

In the Preview window for Network, it shows an Array:

在此处输入图片说明

I cannot get an array of , in this example, 3 objects and get the array.length of 3

Any help will be much appreciated.

在此处输入图片说明

You should collect all your data and return it as one json result and add a correct http-header (suggested by @Flosculus) so that the json format will be recognized:

$results = mysqli_query($link, $sql);
$data = array();

if ($results->num_rows > 0) {
    while ($row = $results->fetch_assoc()) {
        $data[] = array($row['eventDate'], $row['time'] ,['data' => $row['time']])   ;        
    }

    header('Content-Type: application/json');
    echo json_encode($data) ;
} else {
    echo "0 results";
}

I think you have to use JSON.parse() , if you're using jquery so your js script will look like

$.ajax({
url: "trendData.php",
cache: true,
type: "POST",
data: {arr:data},

success: function (data) {
    var data = JSON.parse(data);

    //see length of array
    console.log(data.length);
}
});

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