xmlhttp.send() returns 404 Not Found (Ajax)

xmlhttp.send() returns 404 Not Found (Ajax)

本文关键字:Found Ajax Not returns send xmlhttp      更新时间:2023-09-26

我使用两个文件的示例来练习ajax。我从这个网站复制了代码,但当我尝试运行它时,它在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;
 ?> 

我遇到了一个问题,就像这个问题一样,绝望地砸了我的头,Molle博士在评论中说的话帮助了我。

我有一个PHP("父"文件),其中包括另一个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"。

我希望它能有所帮助!