我终于成功地使用Ajax将SOMETHING从一个页面发送到另一个页面!我正在试图做的是通过从一个PHP文件中的JavaScript文件的阵列,以及JavaScript文件在this.responseText
收到此:从Ajax请求解码JSON数组
<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>
你取回一个HTTP 200状态码回来?使用萤火虫,以确定是否是脚本没有返回或呼叫完全失败的问题。 – 2010-08-26 15:40:01