加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 03:12:30 所属栏目:百科 来源:网络整理
导读:我有这个ajax代码 xmlhttp = new XMLHttpRequest();xmlhttp.onreadystatechange=function(){ if (xmlhttp.readyState==4 xmlhttp.status==200) { document.getElementById('addIO').innerHTML+=xmlhttp.responseText; }}xmlhttp.open("GET","http://localhos
我有这个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>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读