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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10474259/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 01:30:28  来源:igfitidea点击:

how can I return array from php to javascript using ajax

phpjavascriptajax

提问by William Kinaan

i have this ajax code

我有这个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();

and I have a php array

我有一个 php 数组

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

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

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

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

回答by u283863

PHP

PHP

echo json_encode($cars);

JavaScript

JavaScript

Native:

本地

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

With jQuery:

使用 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>:

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

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

回答by Marc B

Use JSON:

使用JSON

echo json_encode($cars);