function HttpRequest(sUrl,fpCallback)
{ this.request = this.createXmlHttpRequest();
this.request.open("GET",sUrl,true); var tempRequest = this.request;
function request_readystatechange()
{ if (tempRequest.readyState == 4)
{ if (tempRequest.status == 200)
{
fpCallback(tempRequest.responseText);
}
else if (tempRequest.status == 0)
{ alert("An error occurred trying to contact the server."); }
else
{ alert("错误"); }
}
} this.request.onreadystatechange = request_readystatechange;}HttpRequest.prototype.createXmlHttpRequest = function ()
{
if (window.XMLHttpRequest)
{ var oHttp = new XMLHttpRequest();
return oHttp; }
else if (window.ActiveXObject)
{ var versions = 
[
"MSXML2.XmlHttp.6.0",
"MSXML2.XmlHttp.3.0"
];
for (var i = 0; 1 < versions.length; i++)
{ try
{ var oHttp = new ActiveXObject (versions[i]);
return oHttp; }
catch (error)
{ //do nothing here }
}
} return null;}HttpRequest.prototype.send = function ()
{ this.request.send(null);}<html>
<head>
<script type="text/javascript" src="httprequest.js"></script>
</head>
<body>
<script type="text/javascript">
function handleData(sResponseText)
{
alert(sResponseText);
}
var url = "http://localhost/test1/111.php?userName=" + "aaa";
var request = new HttpRequest(url,handleData);
request.send();
</script>
</body>
</html>
<?php
$a = $_GET[userName];
return $a;
?>
我少知道错在哪里了。xmlhttprequestjavascripthtmlurlphp

解决方案 »

  1.   

    <?php
    $a = $_GET[userName];
    echo $a;
    ?>
      

  2.   

    有什么错误吗?谷歌下测试没有问题。你看下你的url php 端是否能够获取到名称。
      

  3.   


    url地址根本就没有发送到PHP页面
      

  4.   

    是不是路径问题。http://localhost/test1/111.php    这个可以访问不
      

  5.   


     alert("An error occurred trying to contact the server.");
      

  6.   

    经测前端代码没有问题,但不排除url可能存在问题。
    请使用chrome运行实例,并查看控制台有无报错输出。
    倘若没有,请查看network选项卡下有无XHR请求产生。
      

  7.   

    status为0表示异步请求还没发送,请楼主检测一下当前浏览器的地址栏也是http://localhost,确保不是file:///,file协议下无法使用XHR。
      

  8.   


    <?php
    $a = $_GET["userName"];
    echo $a;
    ?>userName加上引号
      

  9.   

    您好,非常感谢您回答。给您20分。我还有两个问题,如果方便的话请帮我一下。1 我用localhost的路径为什么不管用。127.0.0.1就管用了。
    2.为什么 只能用 echo 返回,不能用return返回
      

  10.   

    您好,非常感谢您回答。给您20分。我还有两个问题,如果方便的话请帮我一下。1 我用localhost的路径为什么不管用。127.0.0.1就管用了。
    2.为什么 只能用 echo 返回,不能用return返回您好,
    1 localhost是可以发起xhr请求的,但是要保证ajax请求的url与当前地址栏中的url的域名部分相同。说简单点就是不能跨域请求。
    2. 因为在php中,echo 是将内容输出到http管道中,也就是作为http报文主体内容,返回给正在等待的浏览器。return 则是函数或者方法返回某个值的语法。如果在php的全局处return,则会中止后边的代码执行;如果当前php文件是include或者require包含进来的,该处return的值将作为require或include的返回值。
      

  11.   

    您好,非常感谢您回答。给您20分。我还有两个问题,如果方便的话请帮我一下。1 我用localhost的路径为什么不管用。127.0.0.1就管用了。
    2.为什么 只能用 echo 返回,不能用return返回您好,
    1 localhost是可以发起xhr请求的,但是要保证ajax请求的url与当前地址栏中的url的域名部分相同。说简单点就是不能跨域请求。
    2. 因为在php中,echo 是将内容输出到http管道中,也就是作为http报文主体内容,返回给正在等待的浏览器。return 则是函数或者方法返回某个值的语法。如果在php的全局处return,则会中止后边的代码执行;如果当前php文件是include或者require包含进来的,该处return的值将作为require或include的返回值。谢谢您