我有这个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数组
$汽车=阵列( “萨伯”,“沃尔沃”,“BMW”,“丰田”);
我如何将数组$cars发送到我的javascript?
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 });
UPDATE
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>