可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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:
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:
and as body response:
xMCdDNb7Pvf3zPNohmkQ2012-03-17 01:15:22image/jpegfalse102476820805300http://i.imgur.com/xMCdD.jpghttp://imgur.com/xMCdDhttp://imgur.com/delete/Nb7Pvf3zPNohmkQhttp://i.imgur.com/xMCdDs.jpghttp://i.imgur.com/xMCdDl.jpg
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:
Thanks in advance.
回答1:
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:
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.
回答2:
Perhaps give this a try? I use this with a google maps store locator. I notice $.parseXML actually does this internally, but its within a try/catch, and its saying your data
is null (which is weird?)
var xml; if (typeof data == "string") { xml = new ActiveXObject("Microsoft.XMLDOM"); xml.async = false; xml.loadXML(data); } else { xml = data; }
From 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; },
回答3:
I have used that plugin before. If I recall this right it is using an iframe to fetch the information and then it is reading the content in the iframe. The content is stored in the property responseText. But IE may have stricter rules than other browsers. Have you tried printing out the value of data.responseText?
If the value is not a XML string. I hate to say it but the API isn't made for Javascript. What I've learned is that JSONP with manipulating the script tags is the best way to do cross domain XHR. Which I don't think this plugin does.
回答4:
js
code:
$(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('
'); } }); });
php
code:
$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; ?>