我有这个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?
答案 0 :(得分:15)
echo json_encode($cars);
<强>本地强>:
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);