AJAX没有响应
所以我试图只是警告我的“你好”从我的PHP文件,它非常简单,但它不工作的原因。AJAX没有响应
JS
function dynamic()
{
if(window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
else
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function()
{
if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
window.alert(xmlhttp.responseText);
}
}
xmlhttp.open("POST", "hello.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
}
dynamic();
PHP
<?php
echo "Hello";
?>
HTML
<html>
<head>
<title>Hello</title>
<script src="dynamic.js"></script>
</head>
<body>
test
</body>
</html>
我不能得到的警告框,提醒我的“赫尔LO”。它应该直接来自responseText。
所以我总是要发送一些东西,即使是空的? – 2012-03-21 05:40:32
@Howdy_McGee是的,因为它发送请求 – 2012-03-21 05:43:24
@david你是。我总是使用'null'来获取GET,所以我写了这个。其实它并不需要它。 – 2012-03-21 05:52:45
试试这个:
function dynamic()
{
if(window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
else
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function()
{
if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
window.alert(xmlhttp.responseText);
}
}
xmlhttp.open("GET", "hello.php", true);
xmlhttp.send(null);
}
dynamic();
我想你忘了发送请求:
试试这个
xmlhttp.setRequestHeader("Content-type", "text/plain");
或
xmlhttp.setRequestHeader("Content-type", "text/html");
代替
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
,你必须把
xmlhttp.send(null);
只是出于好奇:如果您不发送任何数据,为什么使用POST请求? GET更简单,更直接。 – David 2012-03-21 05:40:58