为什么这不起作用?当 Ajax 代码未包装在 function xmlhttpGet()
中时,它确实可以工作:PHP 返回被调用的页面并将其插入到 DIV 中。在此代码中,我将代码包装到函数 xmlhttGet() 中,但没有任何反应。请求的页面未加载到 DIV 中。
<html><head><title>AJAX GET </title>
</head><body><center />
<h1>Loading a web page into a DIV</h1>
<FORM id="form" method="post" action="">
<b> Enter argument: </b>
<input size="40" name="q" id="q" value="">
<INPUT TYPE="submit" id="submit" VALUE="Submit" onClick="xmlhttpGet(this.form)">
<INPUT TYPE="reset" VALUE="Reset">
</FORM>
<div id='info'>This sentence will be replaced</div>
<script>
function xmlhttpGet(form)
{
nocache = "&nocache=" + Math.random() * 1000000
request = new ajaxRequest()
var $q = form.q.value
request.open("GET", "urlget.php?url=amazon.com/gp/aw" + nocache, true)
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)
}
}
}// END xmlhttpGet
request.send(null) ;
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
}// ajaxRequest
</script></body></html>
[编辑]
onClick 触发正常。我已经通过将警报插入到函数中进行了验证。
[编辑2]
我想如果我也显示 PHP 位会有帮助
<?php // urlget.php
if (isset($_GET['url'])) {
echo file_get_contents("http://".sanitizeString($_GET['url']));
}
else {
echo "problem!" ; // [edited line]
}
function sanitizeString($var) {
$var = strip_tags($var);
$var = htmlentities($var);
return stripslashes($var);
}
?>
最佳答案
您必须在脚本中的某个位置调用 xmlhttp Get()
才能使其“运行”
关于php - Javascript 表单和对 PHP 的 Ajax 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5503862/