[英]sending an array to javascript through ajax
I am trying to send an array from PHP to Ajax in javascript. 我正在尝试将JavaScript中的数组从PHP发送到Ajax。 my array in PHP file "myphp.php" is $parts and is multidimentional.
我在PHP文件“ myphp.php”中的数组是$ parts并且是多维的。
I have used both echo $parts and echo json_encode($parts) none works for me. 我已经用过echo $ parts和echo json_encode($ parts)对我都不起作用。 $parts has 2 rows and 2 columns this is the result of var_dump:
$ parts有2行2列,这是var_dump的结果:
array(4) { [0]=> array(3) { [0]=> string(13) "1350655763.12" [1]=> string(2) "25" [2]=> string(1) " " } [1]=> array(3) { [0]=> string(13) "1350655763.12" [1]=> string(2) "26" [2]=> string(0) "" } [2]=> array(1) { [0]=> string(0) "" } [3]=> array(1) { [0]=> string(0) "" } }
I want to send the hole array to Ajax but just display $parts[0][0] on the web page. 我想将孔阵列发送给Ajax,但只在网页上显示$ parts [0] [0]。 When I use
当我使用
echo $parts
in myphp.php file: "Array" name is displayed on the web page When I use 在myphp.php文件中:当我使用时,“ Array”名称显示在网页上
echo json_encode($parts)
in myphp.php file: all components of the array are displayed instead of the first one 在myphp.php文件中:显示数组的所有组件,而不是第一个组件
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<script>
function getXMLHttp()
{
var xmlHttp
try
{
//Firefox, Opera 8.0+, Safari
xmlHttp = new XMLHttpRequest();
}
catch(e)
{
//Internet Explorer
try
{
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e)
{
try
{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e)
{
alert("Your browser does not support AJAX!")
return false;
}
}
}
return xmlHttp;
}
function MakeRequest()
{
var xmlHttp = getXMLHttp();
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4)
{
var parts=JSON.parse(xmlHttp.responseText);
document.getElementById('ResponseDiv').innerHTML = parts[0][0];
}
}
xmlHttp.open("GET", "myphp.php", true);
xmlHttp.send(null);
}
result=MakeRequest();
</script>
</head>
<body>
<div id='ResponseDiv'>
This is a div to hold the response.
</div>
</body>
</html>
How should I change these codes to just get parst[0][0] on the webpage? 我应该如何更改这些代码以仅在网页上获取parst [0] [0]? Thanks in advance for you help
预先感谢您的帮助
you need to use JSON.parse on at javascript and json_encode at php. 您需要在javascript上使用JSON.parse和在php上使用json_encode 。
PHP: PHP:
$parts = array();
....
echo (json_encode($parts));
Javascript: 使用Javascript:
var parts = JSON.parse(xmlHttp.responseText);
Optionally, on your PHP page, you can also define header('Content-type: application/json');
(可选)在PHP页面上,您还可以定义
header('Content-type: application/json');
You should parse your json encoded data into javascript before use it. 使用前,您应将json编码的数据解析为javascript。 Please check json here
请在这里检查json
http://www.json.org/js.html http://www.json.org/js.html
Please try this code: 请尝试以下代码:
result = MakeRequest();
var myObject = eval('(' + result + ')');
alert(myObject[0][0]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.