使用php的AJAX请求的responseText是空的

时间:2013-03-29 14:58:56

标签: php ajax responsetext

我非常喜欢AJAX Requesting和PHP,我有一个问题: 我正在尝试对我的wamp服务器上的php文件执行GET请求但是它的responseText保持空白,当我在readyState为4时检查状态代码时,它为0。

当我在浏览器中执行php文件时,它会返回我的期望:带有JSON对象的数组。

有谁知道答案?

Javascript代码:

this.getCars = function(id) {
    var xmlhttp;
    if (window.XMLHttpRequest) {
        xmlhttp=new XMLHttpRequest();
    }
    else {
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    var that = this;
    xmlhttp.onreadystatechange=function()
    {

        if (xmlhttp.readyState==4)
        {
            alert(xmlhttp.status);
            //that.lastTableCars = JSON.parse(xmlhttp.responseText);

        }
    }
    xmlhttp.open("GET","http://localhost/getCars.php?q="+id,true);
    xmlhttp.send(null);
}

PHP:

<?php
$q=$_GET["q"];
$con = mysql_connect('127.0.0.1', 'root', 'root');
if (!$con)
{
    die('Could not connect: ' . mysql_error());
}

mysql_select_db("autobay", $con);

$sql= "SELECT * FROM autoos WHERE id = '".$q."'";

$result = mysql_query($sql);
$info = [];
while( $row = mysql_fetch_assoc( $result)){
    $info[] = $row; 
}

echo json_encode($info);

mysql_free_result($result);
mysql_close();

1 个答案:

答案 0 :(得分:2)

首先,使用jQuery来帮助排除故障。它会让你的生活变得更加轻松。即使您最终想要使用原始xmlhttprequest,我也建议使用jQuery来排除代码中的xmlhttprequest问题,并更快地研究真正的问题。

翻译:我对原始xmlhttprequest不满意,所以为了帮助你切换到jQuery。您可以在问题解决后返回! =)

this.getCars = function(id) {
   $.get("/getCars.php?q="+id, function(data) {
      alert("response from server: " + data);
   });
}

http://api.jquery.com/jQuery.get/

另外,请确保您使用Chrome开发工具或Firebug检查服务器的响应,可能是因为它失败了。

<强>更新

确保您的HTML页面(即进行ajax调用)和PHP脚本在同一个域(localhost)上运行。我注意到您在ajax调用中指定了完整的http://localhost网址。 Ajax不能跨域工作(虽然有解决方法,如果你真的需要这样跨域,请查看JSONP)。最好的办法是从与PHP脚本相同的域中加载HTML页面。

更新2:

实际问题是OP正在从他的计算机上的文件夹(而不是http://localhost)加载HTML并尝试对http://localhost进行ajax调用。 ajax调用失败,因为这在技术上是跨域的。

相关问题