【问题标题】:Problem in getting Http Response in chrome在 chrome 中获取 Http 响应的问题
【发布时间】:2012-04-02 21:46:51
【问题描述】:

我试图在 javascript 中从 php web 服务获取 http 响应,但在 Firefox 和 chrome 中获取 null。请告诉我我的代码在哪里做错了,

function fetch_details()
{
 if (window.XMLHttpRequest)
 {
  xhttp=new XMLHttpRequest()
  alert("first");
 }
else
 {
  xhttp=new ActiveXObject("Microsoft.XMLHTTP")
  alert("sec");
 }
 xhttp.open("GET","url.com",false);
 xhttp.send("");
 xmlDoc=xhttp.responseXML;
 alert(xmlDoc.getElementsByTagName("Inbox")[0].childNodes[0].nodeValue);
}

我也尝试过使用 ajax,但没有得到 http 响应这是我的代码,请指导我

var xmlhttp = null;
var url = "url.com"; 
if (window.XMLHttpRequest) 
{ 
   xmlhttp = new XMLHttpRequest(); 
   alert(xmlhttp); //make sure that Browser supports overrideMimeType 
   if ( typeof xmlhttp.overrideMimeType != 'undefined') 
   {                     
      xmlhttp.overrideMimeType('text/xml'); 
   } 
} 
else if (window.ActiveXObject) 
{ 
   xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
else
{ 
   alert('Perhaps your browser does not support xmlhttprequests?'); 
} 

xmlhttp.open('GET', url, true);
xmlhttp.onreadystatechange = function() {

if (xmlhttp.readyState == 4)
{
   alert(xmlhttp.responseXML);
} 
};

}

// 发出实际的请求 xmlhttp.send(null);

我得到 xmlhttp.readyState = 4 xmlhttp.status = 0 xmlhttp.responseText = ""

请告诉我哪里出错了

【问题讨论】:

  • 请对您的代码格式进行一些处理。文本字段上方有一个“010101”按钮,用于将代码标记为代码。即使我会为你点击它,这段代码还是太乱了,所以这次我就不打扰了。
  • 您是在进行跨域请求吗?这是获取状态码 0 的常见情况。

标签: javascript xmlhttprequest


【解决方案1】:

您正在执行跨域请求。

您只能向同一主机发出 xmlhttp 请求。

【讨论】:

    【解决方案2】:

    我什么都看不懂,但 Chrome 有一个 JavaScript 控制台,它可能会告诉你你做错了什么。

    【讨论】:

    • 我不知道为什么会得到 http.status = 0
    • 我认为是跨域问题
    【解决方案3】:

    这是一个cross-domain 问题,要解决它,服务器响应标头应包含"access-control-allow-origin"

    如果您的服务器是用 PHP 编码的,则标头应类似于以下示例:

    <?php
        header('Content-type: text/html');
        header('Access-Control-Allow-Origin: *');
        $uri = 'http'. ($_SERVER['HTTPS'] ? 's' : null) .'://'. $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
        echo('<p>This information has come from <a href="' . $uri . '">' . $uri . '</a></p>');
    ?>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-07
      • 2022-06-28
      • 2012-11-07
      • 2016-12-17
      • 1970-01-01
      • 2012-05-24
      相关资源
      最近更新 更多