简体   繁体   中英

how to return an array from php to ajax response in javascript

how to return an array in php to ajax call,

ajax call :

$.post('get.php',function(data){
alert(data)

});

get.php

$arr_variable = array('033','23454')
echo  $arr_variable;

in the alert(data), it is displaying as Array (ie only text), when i display data[0], 1st letter of Array ie A is displaying.

Any suggestions ? where i have done wrong

Use to encode the array like

$data['result'] = $arr_variable;
echo json_encode($data);
exit;

And in the success function try to get it like parseJSON like

$.post('get.php',function(data){
    var res = $.parseJSON(data);
    alert(res.result)
});

instead of echo $arr_variable; use echo json_encode($arr_variable); and then in jQuery you can access it like an object.

Once it is an object, you can access it as data[0] and so forth.

$.post('get.php',function(data){
    $.each(data, function(d, v){
        alert(v);
    });
});

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