如何使用ajax将数组从php返回到javascript

时间:2012-05-06 21:01:32

标签: php javascript ajax

我有这个ajax代码

xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function(){
    if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
        document.getElementById('addIO').innerHTML+=xmlhttp.responseText;
    }
}
xmlhttp.open("GET","http://localhost/Mar7ba/Ontology/getRelatedConceptsAndRelations/3/TRUE",true);
xmlhttp.send();

我有一个php数组

$cars=array("Saab","Volvo","BMW","Toyota");

如何将数组$ cars发送到我的javascript?

2 个答案:

答案 0 :(得分:15)

PHP

echo json_encode($cars);

的JavaScript

<强>本地

var foo = JSON.parse(xmlhttp.responseText);

使用jQuery

var foo = $.parseJSON(xmlhttp.responseText);
//or
$.getJSON("url", function(data){
    //data is your array
});

更新

if(xmlhttp.readyState==4 && xmlhttp.status==200){
     //document.getElementById('addIO').innerHTML+=xmlhttp.responseText;
    var cars = JSON.parse(xmlhttp.responseText);  //cars will now be the array.
     //Do whatever you want here.
    $("#addIO").html(cars.join(", "));     //Join array with ", " then put it in addIO
}

如果您想使用jQuery,请将其放在<head>

<script type="text/javascript" src="link/to/the/file/jquery.js"></script>

答案 1 :(得分:5)

使用JSON

echo json_encode($cars);