【问题标题】:IE9 refuses to process XML responseIE9 拒绝处理 XML 响应
【发布时间】:2012-04-02 13:00:34
【问题描述】:

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

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

更新 - tl;dr

我创建了一个带有临时密钥的小提琴,以便你们更容易看到问题: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 的第一个错误消失了,但我无法获得预期的结果(在这种情况下,id="uploadOutput" 的 div 中的 image/jpeg )。

当我在 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

作为身体反应:

<?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>

提前致谢。

【问题讨论】:

  • 您是否使用 Fiddler2 运行 IE 来检查结果。 IE 在内容编码标头等方面可能非常严格......我怀疑虽然文档在文档中标记为 UTF-8,但服务器可能没有指定字符集。其他浏览器通常会默认使用 UTF-8。
  • 我这样做了,结果也是一样。我没有在这里发布它,因为它需要一个密钥才能工作,所以在这种情况下它没有实际用途。不过,我会稍后再试。
  • 我刚刚添加了一个带有临时密钥的小提琴。
  • 顺便说一句,我不确定这是否与编码有关,因为此处给出的示例 (malsup.com/jquery/form/#file-upload) 可以正常工作。
  • 您发布的 XML 无效:第 5 行,“”没有结束“>”。或者这只是一个发布错字?

标签: javascript jquery xml ajax internet-explorer-9


【解决方案1】:

IE 在接受 XML 和解析 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() 设置手动设置要返回的标头:

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

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

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

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

【讨论】:

  • 我认为你成功了。没有调用 success() 并且 complete() 运行但显然没有得到任何响应。根据您的评论,它缺少 text/xml 标头。我检查了 IE 中的标题,而是看到内容类型:应用程序/xml。这还不够吗?无论如何,这是服务器问题,对吧?
  • 收到 application/xml 作为响应头时是否有效?如果没有,我在我的问题中包含了一个快速编辑,它手动设置 AJAX 请求的响应标头
  • 好吧,它似乎更接近解决方案,但不幸的是,添加任何这些 sn-ps 都会引发加载 imgur.com 的 xml 页面(在 Chrome、Firefox 和 IE 中)。成功并没有开始。
  • 哦......只有当我将它添加到“beforeSubmit”函数时才会发生这种情况,但如果我将它们与其余部分一起放在:“success: afterSuccess, complete: afterCompletion, dataType: ($ .browser.msie) ? "text" : "xml", 接受:{ xml: "text/xml", text: "text/xml" }" 它什么也没发生。顺便说一句, 设置正确。
  • 不要添加beforeStart 设置,只包括我指定的设置。此外,我使用 Chrome 和 IE9 访问了您的 jsFiddle,并且都可以正常工作。我在 IE9 中跟踪了响应,它以 200 的响应返回 application/xml(即它是成功的)。转到设置并启用 IE9 中的开发人员工具。您可以通过转到“网络”选项卡并单击“开始捕获”来跟踪网络响应。当您在 IE9 中发送表单时会得到什么响应?
【解决方案2】:

js代码:

    $(function() {
        $('#uploadForm').ajaxForm({
            dataType : 'xml', // OR $('#uploadResponseType option:selected').val()
            beforeSubmit : function(a, f, o) {
                $('#uploadOutput').html('Submitting...');
            },
            success : function(data) {
                var original = $(data).find('links').find('original').text();
                $('#uploadOutput').html('<img src="' + original + '" alt="" />');
            }
        });
    });

php代码:

<?
    $api_key = "****************************";

    $file    = getcwd() . '/' . basename( $_FILES['image']['name'] );
    move_uploaded_file($_FILES['image']['tmp_name'], $file);

    $handle  = fopen($file, "r");
    $data    = fread($handle, filesize($file));

    $pvars   = array('image' => base64_encode($data), 'key' => $api_key);
    $post    = http_build_query($pvars);

    $curl    = curl_init();
    curl_setopt($curl, CURLOPT_URL, 'http://api.imgur.com/2/upload.xml');
    curl_setopt($curl, CURLOPT_TIMEOUT, 30);
    curl_setopt($curl, CURLOPT_POST, 1);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $post);
    curl_setopt($curl, CURLOPT_HTTPHEADER, array("Content-type: application/x-www-form-urlencoded"));
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $xml = curl_exec($curl); 
    curl_close ($curl);

    unlink($file);

    header('Content-type: text/xml'); 
    echo $xml;
?>

【讨论】:

【解决方案3】:

我以前用过那个插件。如果我记得这是正确的,它是使用 iframe 来获取信息,然后它正在读取 iframe 中的内容。内容存储在属性 responseText 中。但 IE 可能比其他浏览器有更严格的规则。你试过打印出 data.responseText 的值吗?

如果值不是 XML 字符串。我不想这么说,但 API 不是为 Javascript 制作的。我了解到的是,带有操作脚本标签的 JSONP 是执行跨域 XHR 的最佳方式。我认为这个插件不会。

【讨论】:

  • 感谢您的回答。当我尝试打印 data.responseText 时,我在 IE9 中一无所获(尽管它在其他浏览器中正常工作),但响应是有效的 XML。此外,插件文档页面中的示例可以在 IE9 中使用,所以如果这是由插件特定的东西引起的,我会感到非常惊讶。
  • 这证实了“无法访问 iframe”假设 - 数据返回,但无法读取。
  • API 不是为客户端代码而设计的。所以唯一的方法是使用服务器端代码获取 XML 并格式化它。
【解决方案4】:

也许试试这个?我将它与谷歌地图商店定位器一起使用。我注意到 $.parseXML 实际上在内部执行此操作,但它在 try/catch 中,并且它说您的 data 为空(这很奇怪?)

      var xml;
     if (typeof data == "string") {
       xml = new ActiveXObject("Microsoft.XMLDOM");
       xml.async = false;
       xml.loadXML(data);
     } else {
       xml = data;
     }

来自 jQuery:

// Cross-browser xml parsing
parseXML: function( data ) {
    var xml, tmp;
    try {
        if ( window.DOMParser ) { // Standard
            tmp = new DOMParser();
            xml = tmp.parseFromString( data , "text/xml" );
        } else { // IE
            xml = new ActiveXObject( "Microsoft.XMLDOM" );
            xml.async = "false";
            xml.loadXML( data );
        }
    } catch( e ) {
        xml = undefined;
    }
    if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) {
        jQuery.error( "Invalid XML: " + data );
    }
    return xml;
},

【讨论】:

  • 我认为非 IE 部分有问题,因为现在我得到一个未捕获的异常(无效的 XML:[object Document]),但是在 IE9 中我没有看到任何错误,即使响应正文显示正确的 XML 文档,它也不会做任何事情。
猜你喜欢
  • 1970-01-01
  • 2019-11-25
  • 2016-05-04
  • 2014-07-15
  • 2019-05-15
  • 2018-06-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多