【问题标题】:Issue with window.XMLHttpRequest in Internet Explorer (works in Chrome)Internet Explorer 中的 window.XMLHttpRequest 问题(适用于 Chrome)
【发布时间】:2013-04-14 15:03:52
【问题描述】:

我有一个简单的脚本,如下:

function functionName(code){
var xmlhttp;
if (window.XMLHttpRequest)
    {// code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
    }
else
    {// code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
xmlhttp.onreadystatechange=function()
    {
    if (xmlhttp.readyState==4)
        {
        var result=xmlhttp.responseText;
        if (result=="FAIL")
        {
            // Alert 
        }
        else
        {
            // Alert
        }
        }
}
xmlhttp.open("GET","script.php?q="+code,true);
xmlhttp.send();
}

我在页面上有一个按钮,带有一个调用该函数的 onclick 命令:

<form action="">
<table><tr><td><input type="text" name="code" id="code" size="4"></td><td><a onclick="functionName(code.value)"><img src="images/button.png" /></a></td></tr></table><br />

从表单输入中发送一个代码,如果 script.php 返回“FAIL”并在所有其他情况下返回另一个警报,则给出一个响应(它的作用不止于此,但取出所有其他内容并使用警报进行故障排除)。该代码在 Chrome 中运行良好,但在 Internet Explorer 中运行良好。我对此很陌生,所以不知道如何调试它,有什么明显的东西会导致浏览器之间出现问题吗?感谢您的帮助。

编辑:

我已将其范围缩小到实际上是导致问题的 onclick,因此我将研究为什么这在 IE 中不起作用...

编辑 2:

结果它看起来像一个 IE10 怪癖 - 适用于所有其他版本,并且在兼容性视图中,不知道为什么

【问题讨论】:

  • 考虑使用 JQuery 或其他 API,使用不同的代码为不同的浏览器解决许多问题。

标签: javascript internet-explorer google-chrome xmlhttprequest


【解决方案1】:

.open 清除 IE 中任何先前设置的 onreadystatechange 处理程序。您的代码应如下所示:

var xmlhttp = ...;
xmlhttp.open(...);
xmlhttp.onreadystatechange = ...;
xmlhttp.send(...);

【讨论】:

  • 另请注意,不再支持 IE6 及更早版本。您可以使用var xmlhttp = new XMLHttpRequest() 就可以了。除非你在中国。
【解决方案2】:

当您使用 jquery 标记您的问题时 - 我建议您使用更简单的方法而不是复杂的方法(让 jquery 管理跨浏览器兼容性

function functionName(code){
  $.get("script.php?q="+code,function(result){
    if (result=="FAIL"){
        // Alert 
    }
    else{
        // Alert
    }
  });
}

编辑:

更新您的a

<a href='#' id='getCode'>

脚本:

$(document).ready(function(){
   $('#getCode').on('click',function(){
      var code = $('#code').val();
      $.get("script.php?q="+code,function(result){
        if (result=="FAIL"){
            // Alert 
        }
        else{
            // Alert
        }
      });
   });
});

【讨论】:

  • 感谢您的帮助,我已经用上面的代码替换了代码,但是虽然它在 Chrome 中运行良好,但当我单击按钮时它仍然没有在 IE 中执行任何操作。好像 OnClick 函数调用不起作用 - IE10 是否存在明显的兼容性问题?
  • 嗯,不幸的是,现在什么都没得到 - Chrome 或 IE。单击只会在 URL 中添加一个“#”。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-08-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多