Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

This is a question in relation to this one.

In UPDATE II, I added a script based on Jamie's feedback.

UPDATE - tl;dr:

I created a fiddle with a temporary key so you guys can see the problem more easily: http://jsfiddle.net/S6wEN/.

As this question was getting too long, this is a summary.

  • I tried to use imgur API to update an image via cross domain XHR.
  • In order to abstract details in the implementation, I'm using Jquery Form Plugin (obviously, it's contained in the fiddle).
  • Works great in Chrome, Firefox, etc but it doesn't work in IE9.
  • The expected result is to update the image and retrieve image type.

You can still find the details below.

Thanks


I have this 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>

So basically, I have a form to upload an image to imgur via cross domain XHR. In order to manage the nasty details, I'm using Jquery Form Plugin, which works well. However, when I try to send an image to imgur and receive an xml response, it doesn't work as expected in IE9 (I haven't tested in IE8 but I don't expect great news). It works great in Chrome and Firefox. This is the javascript part:

(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'));

        }
    });
})();  

In IE9 I receive the following errors:

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

XML5619: Incorrect document syntax. 
, line 1 character 1

I also used the example given in Jquery Form Plugin's page, which uses only Javascript but it doesn't help. Obviously, the first error referring to Jquery disappears but I can't obtain the expected results (in this case, image/jpeg in the div with id="uploadOutput" ).

When I look at the console in IE9, I get this:

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

and as body response:

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

which is all fine, but for some reason, I can't process that information into the HTML page. I validated the XML, just to be sure that wasn't the problem. It is valid, of course.

So, what's the problem with IE9?.

UPDATE:

Another way to fetch XML which works in Chrome and Firefox but not in 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);
        }
    });
})();  

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

Thanks in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
157 views
Welcome To Ask or Share your Answers For Others

1 Answer

IE is notoriously fussy when it comes to accepting XML and parsing it. Try something like this:

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

Also,use alert() throughout debugging to provide feedback on what information is being passed through at all times.

EDIT

The crucial thing is ensure your XML file is 'well-formed', i.e. it must not contain any syntax errors. You need to begin the XML file with:

<?xml version="1.0"?>

It's not so much a server issue because, the errors come from your browser (i.e. Internet Explorer) because it thinks the XML is malformed. The error comes from your browser and indicates that your XML is malformed. You can manually set what headers you want returned with these $.ajax() settings:

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

Or another way to do the same thing is to ask for a particular header:

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

The difference between the content-types application/xml and text/xml are minor (it's based on each XML's charset), but if you want to know you can read this post.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...