我终于成功地使用Ajax将一些东西从一个页面发送到另一个页面!我要做的是将一个数组从一个PHP文件传递到一个Javascript文件,并且Javascript文件在this.responseText中接收到这个
<html>
<head>
<script type="text/javascript">
var jsonArray = ["chickens","horses","cows","werewolves","zombies","vampires","phantoms","U.S. Congressmen","performance artists","pieces of fencepost","barnhouses","robots","cyborgs"]
</script>
</head>
</html>我试着对结果运行eval()和alert,但没有显示结果。如何从this.responseText成功地提取数组
到目前为止,编辑是我的函数:
/*
* Function: selectVictim
* Called from function laserOn()
*
* Selects a random victim from a list of victims
*
* @return String: victim
*/
function selectVictim()
{
var params = "url=queenofsheep.com/Sheep/victims.php";
var request = new ajaxRequest();
request.open("POST", "victims.php", true);
request.setRequestHeader("Content-Type",
"application/x-www-form-urlencoded");
request.setRequestHeader("Content-Length", params.length);
request.setRequestHeader("Connection", "close");
request.onreadystatechange = function ()
{
if (this.readyState == 4)
{
if (this.status == 200)
{
if (this.responseText != null )
{
var vicArray = eval('('+this.responseText+')');
var numVic = Math.floor(Math.random() * (vicArray - 1));
alert(vicArray);
}
else alert("Ajax error: No data received");
}
else alert("Ajax Error: " + this.statusText);
}
}
request.send(params);
} 第二编辑包含数组的文件(在PHP中)如下:
<html>
<head>
<?php
$victims = array(
// Animals
"chickens",
"horses",
"cows",
// Supernatural
"werewolves",
"zombies",
"vampires",
"phantoms",
// Human
"U.S. Congressmen",
"performance artists",
// Inanimate, non-mechanical
"pieces of fencepost",
"barnhouses",
// Mechanical
"robots",
"cyborgs"
);
?>
<script type="text/javascript">
var jsonArray = <?php echo json_encode($victims); ?>
</script>
</head>
</html>发布于 2010-08-26 15:40:01
如果您的php页面返回您报告的所有文本(与etc.)然后,您的输出不是JSON对象,而是一个html页面。您的响应应该只包含序列化的JSON对象(以及正确的http响应头).
一旦“清理”了输出,就可以使用JSON2库来解析对象:http://www.json.org/js.html
var myObject = JSON.parse(myJSONtext);发布于 2010-08-26 15:41:42
这看起来不像是来自服务器的正确的JSON响应,因为它包含HTML代码,然后是一块javascript。响应应该只包含包含数据的javascript代码,如
var data = ["chickens","horses","cows","werewolves","zombies"]";然后,可以对字符串进行eval(),然后它就可以工作了。
如前所述,eval()可能不安全,因此,如果使用jQuery,可以使用安全的$.parseJSON函数。
要正确返回JSON,不要在页面中输出HTML,只需执行以下操作
<?php
$victims = ...; // fill array
echo json_encode($victims);
?>发布于 2010-08-26 15:33:16
您可以在json.org上使用库,也可以使用eval("(“+ this.responseText + ")");
通常,您希望使用一个库来解析JSON字符串,而不是eval,因为eval通常是不安全的。
https://stackoverflow.com/questions/3576655
复制相似问题