关键词搜索

源码搜索 ×
×

xmlhttp.status为0的原因及其解决方案

发布2017-08-06浏览29890次

详情内容

         先看本地的test.html:

  1. <html>
  2. <head>
  3. <script>
  4. function loadXMLDoc()
  5. {
  6. var xmlhttp = new XMLHttpRequest(); // chrome
  7. xmlhttp.open("GET", "http://localhost/index.php", true);
  8. xmlhttp.send();
  9. xmlhttp.onreadystatechange = function() // 当服务器响应已做好被处理的准备时所执行的任务
  10. {
  11. if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
  12. {
  13. document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
  14. }
  15. }
  16. }
  17. </script>
  18. </head>
  19. <body>
  20. <button type="button" οnclick="loadXMLDoc()">请求数据</button>
  21. <div id="myDiv">hehe</div>
  22. </body>
  23. </html>
        再看apache/php的index.php:

  1. <?php
  2. echo "I love you";
  3. ?>
       结果, 用alert调试发现, xmlhttp.status总是为0, 什么原因呢? 跨域呗! 怎么解决, 改index.php为:

  1. <?php
  2. header("Access-Control-Allow-Origin:*");
  3. echo "I love you";
  4. ?>
      重启apache, 然后就OK了, 如下:



        后面我们会继续介绍浏览器的同源策略和跨域问题。




相关技术文章

点击QQ咨询
开通会员
返回顶部
×
微信扫码支付
微信扫码支付
确定支付下载
请使用微信描二维码支付
×

提示信息

×

选择支付方式

  • 微信支付
  • 支付宝付款
确定支付下载