我正在使用2个文件的样本来练习ajax。我从This Site复制了代码,但是当我尝试运行它时,它在Javascript控制台中出现以下错误404 Not Found
。这是我的HTML和PHP代码: -
HTML文件
<html>
<head>
<script type="text/javascript">
function showResult(str){
if (str.length==0)
{
document.getElementById("livesearch").innerHTML="";
document.getElementById("livesearch").style.border="0px";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("livesearch").innerHTML=xmlhttp.responseText;
document.getElementById("livesearch").style.border="1px solid #A5ACB2";
}
}
xmlhttp.open("GET","livesearch.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form>
<input type="text" size="30" onkeyup="showResult(this.value)" />
<div id="livesearch"></div>
</form>
</body>
</html>
PHP文件
<?php
$xmlDoc=new DOMDocument();
$xmlDoc->load("http://localhost/php/ajax/links.xml");
$x=$xmlDoc->getElementsByTagName('link');
//get the q parameter from URL
$q=$_GET["q"];
//lookup all links from the xml file if length of q>0
if (strlen($q)>0)
{
$hint="";
for($i=0; $i<($x->length); $i++)
{
$y=$x->item($i)->getElementsByTagName('title');
$z=$x->item($i)->getElementsByTagName('url');
if ($y->item(0)->nodeType==1)
{
//find a link matching the search text
if (stristr($y->item(0)->childNodes->item(0)->nodeValue,$q))
{
if ($hint=="")
{
$hint="<a href='" .
$z->item(0)->childNodes->item(0)->nodeValue .
"' target='_blank'>" .
$y->item(0)->childNodes->item(0)->nodeValue . "</a>";
}
else
{
$hint=$hint . "<br /><a href='" .
$z->item(0)->childNodes->item(0)->nodeValue .
"' target='_blank'>" .
$y->item(0)->childNodes->item(0)->nodeValue . "</a>";
}
}
}
}
}
if ($hint==""){
$response="no suggestion";
}
else{
$response=$hint;
}
//output the response
echo $response;
?>
答案 0 :(得分:0)
我正在用一个无可救药的问题猛烈地抨击我的脑袋,并且莫尔博士在评论中说道,帮助了我。
我有一个PHP(“父”文件),其中包含另一个PHP(“son”文件,我们称之为“livesearch.php”,如上面的代码所示),其中包含AJAX的Java脚本。
我的代码与ScoRpion基本相同:
xmlhttp.open("GET","livesearch.php?q="+str,true);
但它应该是:
xmlhttp.open("GET","parent/livesearch.php?q="+str,true);
因为在我的情况下,主PHP页面是“parent.php”,而不是“livesearch.php”。
我希望它有所帮助!