【问题标题】:xmlhttp.send() returns 404 Not Found (Ajax)xmlhttp.send() 返回 404 Not Found (Ajax)
【发布时间】:2012-01-18 06:36:45
【问题描述】:

我正在使用 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;
 ?> 

【问题讨论】:

  • livesearch.php 是否托管在同一台机器上?请记住,您不能(轻松)发送跨域 AJAX 请求。
  • 你确定php-file和html-file放在同一个文件夹吗?但是,您应该在 str 上使用 encodeURIComponent 对其进行编码,然后再将其附加到 URL。

标签: php javascript ajax


【解决方案1】:

我正无可救药地遇到这样的问题,Molle 博士在 cmets 中所说的话帮助了我。

我有一个 PHP(“父”文件),其中包含另一个 PHP(“子”文件,我们将其称为“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”。

希望对你有帮助!

【讨论】:

    猜你喜欢
    • 2018-03-05
    • 2016-03-16
    • 2017-04-29
    • 2020-03-16
    • 2021-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-10
    相关资源
    最近更新 更多