我有一个Ajax文件,我试图与一个PHP文件进行通信,该文件将提供Google主页,并将其放入同一页面的某些HTML中的DIV中。
我已经彻底检查了代码和PHP文件,没有出现任何错误,但我无法理解为什么会发生错误。有人可以帮帮我吗?。提前谢谢。
这是我的ajax
<html>
<head>
<title>Ajax page</title>
</head>
<body>
<h1>AJAX page</h1>
<div id="info">
This content will be changed by default....
</div>
<script type="text/javascript">
params = "url=google.com";
request = new ajaxRequest();
request.open("POST", "ajaxLab.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) document.getElementById("info").innerHTML=this.responseText;
else alert("Ajax error: No data received ");
}
else alert("Ajax error: " + this.statusText);
}
}
request.send(params);
function ajaxRequest()
{
try
{
var request = new XMLHttpRequest();
}
catch(e1)
{
try
{
request = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e2)
{
try
{
request = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e3)
{
request=false;
}
}
}
return request;
}
</script>
</body>
</html>
这是我简单的php文件..
<?php
if(isset($_POST['url'])){
echo file_get_contents("http://".sanitiseVar($_POST['url']));
}
function sanitiseVar($var){
$var = htmlentities($var);
$var = stripslashes($var);
return strip_tags($var);
}
?>
答案 0 :(得分:1)
好的,readyState属性没有崩溃。在我纠正之后工作了!。
答案 1 :(得分:0)
以这种方式更改整个文件:
<html>
<head>
<title>Ajax page</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#info").load("ajaxLab.php", {'url': 'google.com'});
});
</script>
</head>
<body>
<h1>AJAX page</h1>
<div id="info">
This content will be changed by default....
</div>
</body>
</html>
答案 2 :(得分:0)
使用此:
$(document).ready(function(){
$.post("ajaxLab.php",
{
url:"google.com",
// another_param : "its value"
},
function(result){ // Callback function, on success
if(result != null)
$('#info').html(result);
else
alert("Ajax error: No data received ");
}
);
});
请记住在标题中包含jQuery库:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>