我怎样才能从PHP返回阵列使用Ajax的JavaScript阵列、PHP、JavaScript、Ajax

2023-09-10 16:45:38 作者:炽热旳缠绵°

我有这样的阿贾克斯code

  XMLHTTP =新XMLHtt prequest();
xmlhttp.onreadystatechange =功能(){
    如果(xmlhttp.readyState == 4和&安培; xmlhttp.status == 200)
    {
        的document.getElementById('ADDIO)的innerHTML + = xmlhttp.responseText。
    }
}
xmlhttp.open(GET,HTTP://本地主机/ Mar7ba /本体/ getRelatedConceptsAndRelations / 3 /真,真正的);
xmlhttp.send();
 

和我有一个PHP数组

$汽车=阵列(萨博,沃尔沃,宝马,丰田);

我怎样才能发送数组$车我的JavaScript?

解决方案

PHP

 回声json_en code($车);
 
Proe如何使用点阵列

的JavaScript

本机

 变种富= JSON.parse(xmlhttp.responseText);
 

使用jQuery

 变种富= $ .parseJSON(xmlhttp.responseText);
//要么
$ .getJSON(URL,功能(数据){
    //数据阵列
});
 

更新

 如果(xmlhttp.readyState == 4安培;&安培; xmlhttp.status == 200){
     //document.getElementById('addIO').innerHTML+=xmlhttp.responseText;
    VAR轿车= JSON.parse(xmlhttp.responseText); //汽车现在将阵列。
     //做任何你想在这里。
    $(#ADDIO)的HTML(cars.join(,))。 //加入数组,然后把它放在ADDIO
}
 

如果你想使用jQuery,把这个< HEAD>

 <脚本类型=文/ JavaScript的SRC =链接/到/的/文件/ jquery.js和>< / SCRIPT>
 

i have this ajax code

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();

and I have a php array

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

how can i send the array $cars to my javascript ?

解决方案

PHP

echo json_encode($cars);

JavaScript

Native:

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

With 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
}

If you want to use jQuery, put this in <head>:

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

 
精彩推荐
图片推荐