IE9拒绝处理XML响应



这是一个与此相关的问题。

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

更新-tl;dr

我用一把临时钥匙制作了一把小提琴,这样你们就可以更容易地看到问题了:http://jsfiddle.net/S6wEN/.

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

  • 我尝试使用imgur API通过跨域XHR更新图像
  • 为了抽象实现中的细节,我使用了Jquery Form插件(显然,它包含在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>

所以,基本上,我有一个表格上传一个图像到imgur通过跨域XHR。为了管理讨厌的细节,我使用了Jquery表单插件,它运行良好。然而,当我尝试向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

我还使用了JqueryFormPlugin页面中给出的例子,该页面只使用Javascript,但没有帮助。显然,引用Jquery的第一个错误消失了,但我无法获得预期的结果(在这种情况下,div中的image/jpegid="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

和作为身体反应:

<?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有什么问题呢?。

更新:

获取XML的另一种方法可以在Chrome和Firefox中使用,但不能在IE9中使用:

(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和解析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的字符集),但如果您想知道,可以阅读这篇文章。

也许试试吧?我把它和谷歌地图商店定位器一起使用。我注意到$.parseXML实际上在内部这样做,但它在try/catch中,并且它说您的data为null(这很奇怪?)

      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;
},

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

如果该值不是XML字符串。我不想这么说,但API不是为Javascript设计的。我学到的是,带有脚本标记的JSONP是实现跨域XHR的最佳方式。我认为这个插件没有。

  • 演示:http://bit.ly/HondPC

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

最新更新