javascript - IE9 拒绝处理 XML 响应

标签 javascript jquery xml ajax internet-explorer-9

这是一个与 this one 有关的问题.

UPDATE II 中,我根据 Jamie 的反馈添加了一个脚本。

更新 - tl;dr:

我用临时 key 创建了一个 fiddle ,这样你们就可以更容易地看到问题:http://jsfiddle.net/S6wEN/ .

由于这个问题太长了,这是一个总结。

  • 我尝试使用 imgur API 通过跨域 XHR 更新图像。
  • 为了抽象实现中的细节,我使用了 Jquery Form Plugin(显然,它包含在 fiddle 中)。
  • 在 Chrome、Firefox 等中运行良好,但在 IE9 中无法运行。
  • 预期的结果是更新图像并检索图像类型。

您仍然可以在下面找到详细信息。

谢谢


我有这个 HTML:

<body>
<form id="uploadForm" action="http://api.imgur.com/2/upload.xml" method="POST" enctype="multipart/form-data">
    <input type="hidden" name="key" value="MYKEY">
    File: <input type="file" name="image">
    Return Type: <select id="uploadResponseType" name="mimetype">
        <option value="xml">xml</option>
    </select>
    <input type="submit" value="Submit 1" name="uploadSubmitter1">
</form>

<div id="uploadOutput"></div>
</body>

基本上,我有一个表单可以通过跨域 XHR 将图像上传到 imgur。为了管理讨厌的细节,我正在使用 Jquery Form Plugin ,效果很好。但是,当我尝试将图像发送到 imgur 并接收 xml 响应时,它在 IE9 中无法按预期工作(我没有在 IE8 中测试过,但我不希望有什么好消息)。它在 Chrome 和 Firefox 中运行良好。这是 javascript 部分:

(function() {
$('#uploadForm').ajaxForm({
        beforeSubmit: function(a,f,o) {
           o.dataType = $('#uploadResponseType')[0].value;
           $('#uploadOutput').html('Submitting...');
        },

        complete: function(data) {
        var xmlDoc = $.parseXML( data.responseText ),
            $xml = $( xmlDoc );
            $('#uploadOutput').html($xml.find('type'));

        }
    });
})();  

在 IE9 中我收到以下错误:

SCRIPT5022: Invalid XML: null 
jquery.min.js, line 2 character 10890

XML5619: Incorrect document syntax. 
, line 1 character 1

我还使用了 Jquery Form Plugin 页面中给出的示例,该示例仅使用了 Javascript,但没有帮助。显然,第一个引用 Jquery 的错误消失了,但我无法获得预期的结果(在这种情况下, image/jpeg 在 div 中 with id="uploadOutput" ) .

当我在 IE9 中查看控制台时,我得到了这个:

URL Method  Result  Type    Received    Taken   Initiator   Wait‎‎  Start‎‎ Request‎‎   Response‎‎  Cache read‎‎    Gap‎‎
http://api.imgur.com/2/upload.xml   POST    200 application/xml 1.07 KB 7.89 s  click   2808    93  5351    0   0   0

作为 body react :

<?xml version="1.0" encoding="utf-8"?>
<upload><image><name/><title/><caption/><hash>xMCdD</hash>  
<deletehash>Nb7Pvf3zPNohmkQ</deletehash><datetime>2012-03-17 01:15:22</datetime>
<type>image/jpeg</type><animated>false</animated><width>1024</width
<height>768</height><size>208053</size><views>0</views><bandwidth>0</bandwidth></image
<links><original>http://i.imgur.com/xMCdD.jpg</original
<imgur_page>http://imgur.com/xMCdD</imgur_page>
<delete_page>http://imgur.com/delete/Nb7Pvf3zPNohmkQ</delete_page>
<small_square>http://i.imgur.com/xMCdDs.jpg</small_square>
<large_thumbnail>http://i.imgur.com/xMCdDl.jpg</large_thumbnail></links></upload>

这一切都很好,但出于某种原因,我无法将该信息处理到 HTML 页面中。我验证了 XML,以确保这不是问题所在。当然,这是有效的。

那么,IE9 的问题是什么?

更新:

另一种在 Chrome 和 Firefox 中有效但在 IE9 中无效的获取 XML 的方法:

(function() {
$('#uploadForm').ajaxForm({
        dataType: "xml",
        beforeSubmit: function(a,f,o) {
           o.dataType = $('#uploadResponseType')[0].value;
           $('#uploadOutput').html('Submitting...');
        },

        success: function(data) {
            var $xml = $( data ),
                element = $($xml).find('type').text();
                alert(element);
        }
    });
})();  

更新 2:

<!DOCTYPE html>
<html>
    <body>
    <form id="uploadForm" action="http://api.imgur.com/2/upload.xml" method="POST" enctype="multipart/form-data">
        <input type="hidden" name="key" value="00ced2f13cf6435ae8faec5d498cbbfe">
        File: <input type="file" name="image">
        Return Type: <select id="uploadResponseType" name="mimetype">
            <option value="xml">xml</option>
        </select>
        <input type="submit" value="Submit 1" name="uploadSubmitter1">
    </form>

    <div id="uploadOutput"></div>
    </body>
</html>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="jquery.form.js"></script>
​<script>
(function() {

    var options = { 
        // target:        '#output1',   // target element(s) to be updated with server response 
        //beforeSubmit:  showRequest,  // pre-submit callback 
        success: afterSuccess,  // post-submit callback 
        complete: afterCompletion,
        // other available options: 
        //url:       url         // override for form's 'action' attribute 
        type:      'POST',        // 'get' or 'post', override for form's 'method' attribute 
        dataType:  'xml'        // 'xml', 'script', or 'json' (expected server response type) 
        //clearForm: true        // clear all form fields after successful submit 
        //resetForm: true        // reset the form after successful submit 

        // $.ajax options can be used here too, for example: 
        //timeout:   3000 
    }; 

    function process_xml(xml) {
      var type = $(xml).find('type').text() ;
      return type;
      // Find other elements and add them to your document
    }


    function afterSuccess(responseText, statusText, xhr, $form)  { 
        // for normal html responses, the first argument to the success callback 
        // is the XMLHttpRequest object's responseText property 

        // if the ajaxForm method was passed an Options Object with the dataType 
        // property set to 'xml' then the first argument to the success callback 
        // is the XMLHttpRequest object's responseXML property 

        // if the ajaxForm method was passed an Options Object with the dataType 
        // property set to 'json' then the first argument to the success callback 
        // is the json data object returned by the server 
        var $xml = process_xml(responseText);
        console.log('success: ' + $xml);
    } 


    function afterCompletion(xhr,status){
          if(status == 'parsererror'){

            xmlDoc = null;

            // Create the XML document from the responseText string

            if(window.DOMParser) {

              parser = new DOMParser();
              xml = parser.parseFromString(xhr.responseText,"text/xml");

            } else {

              // Internet Explorer
              xml = new ActiveXObject("Microsoft.XMLDOM");
              xml.async = "false";
              xml.loadXML(xhr.responseText);

            }

          }

          console.log('complete: ' + process_xml(xhr.responseText));
    }

$('#uploadForm').ajaxForm(options);
})();  
</script>

提前致谢。

最佳答案

IE 在接受和解析 XML 时非常挑剔。尝试这样的事情:

function process_xml(xml) {
  var type = $(xml).find('type').text() ;
  $('#type').html(type) ;

  // Find other elements and add them to your document
}

$(function() {
  $('#uploadForm').ajaxForm({ 
    dataType: "xml", // 'xml' passes it through the browser's xml parser
    success: function(xml,status) {

      // The SUCCESS EVENT means that the xml document
      // came down from the server AND got parsed successfully
      // using the browser's own xml parsing caps.

      process_xml(xml);

      // Everything goes wrong for Internet Explorer
      // when the mime-type isn't explicitly text/xml.

      // If you are missing the text/xml header
      // apparently the xml parse fails,
      // and in IE you don't get to execute this function AT ALL.

    },
    complete: function(xhr,status){

      if(status == 'parsererror'){

        xmlDoc = null;

        // Create the XML document from the responseText string

        if(window.DOMParser) {

          parser = new DOMParser();
          xml = parser.parseFromString(xhr.responseText,"text/xml");

        } else {

          // Internet Explorer
          xml = new ActiveXObject("Microsoft.XMLDOM");
          xml.async = "false";
          xml.loadXML(xhr.responseText);

        }

        process_xml(xml);

      }
    },
    error: function(xhr,status,error)
    {
      alert('ERROR: ' + status) ;
      alert(xhr.responseText) ;
    }
  });
});

此外,在整个调试过程中使用 alert() 以提供有关始终传递哪些信息的反馈。

编辑

关键是确保您的 XML 文件“格式正确”,即它不得包含任何语法错误。您需要以以下内容开始 XML 文件:

<?xml version="1.0"?>

这不是服务器问题,因为错误来自您的浏览器(即 Internet Explorer),因为它认为 XML 格式错误。该错误来自您的浏览器,表明您的 XML 格式不正确。您可以使用这些 $.ajax() 设置手动设置要返回的 header :

dataType: ($.browser.msie) ? "text" : "xml",
accepts: {
    xml: "text/xml",
    text: "text/xml"
}

或者做同样事情的另一种方法是请求一个特定的标题:

headers: {Accept: "text/xml"},

内容类型 application/xmltext/xml 之间的区别很小(它基于每个 XML 的字符集),但如果你想知道你可以阅读 this post .

关于javascript - IE9 拒绝处理 XML 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9746515/

相关文章:

android - 裁剪ImageViews的Canvas方法

javascript - 通过遍历数组设置JavaScript对象属性

javascript - 在按钮单击和选项上添加一个新的 div 以选择一个选项来显示文本框

Javascript变量局部和全局混淆

javascript - 调用选项卡时调用脏表单检查

jquery - $.get、$.post、$.ajax、$(elm).load到.ashx页面问题

javascript - JS : extracting href and src attributes URLs from DOM as absolute

java - jar.libs.dir 没有被正确覆盖吗?

android - 更改 API 19 及以下版本的 RadioButton 颜色?

JavaScript IE8 : Add a function to a NodeList object