[英]Javascript form & Ajax request to PHP
为什么这不起作用? 当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会被触发。 我已通过将警报插入功能进行验证。
[EDIT2]
我想如果我也显示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);
}
?>
您必须在您的脚本中的某个地方调用xmlhttpGet()
才能使其“运行”
您的xmlhttpget
函数应开始于:
function xmlhttpGet(form)
{
...因为它是在函数中引用变量form
(例如var $q = form.q.value
),但从未var $q = form.q.value
分配值(因此正在从全局范围中创建/提取它)。
的范围this
在你的函数onreadystatechange
会大相径庭取决于浏览器以及它如何被称为-不是一个很好的设计决策,尝试更换this
与request
的功能。
当您的代码未包装在函数中时,它将仅在浏览器解析代码时执行。
一旦将其包装在函数中,它将不会执行,除非显式调用该函数。
如果要使脚本自动运行,请尝试将body标签更改为:
<body onload='xmlhttpGet();'>
如果要通过用户交互来触发该功能,请使用许多事件之一,例如onclick
或onmouseover
或onmousedown
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.