Javascript IE9拒绝处理XML响应
这是一个与……有关的问题 在更新II中,我根据杰米的反馈添加了一个脚本 更新-tl;博士: 我用一把临时钥匙创建了一把小提琴,这样你们就可以更容易地看到问题了: 由于这个问题太长,这是一个总结Javascript IE9拒绝处理XML响应,javascript,jquery,xml,ajax,internet-explorer-9,Javascript,Jquery,Xml,Ajax,Internet Explorer 9,这是一个与……有关的问题 在更新II中,我根据杰米的反馈添加了一个脚本 更新-tl;博士: 我用一把临时钥匙创建了一把小提琴,这样你们就可以更容易地看到问题了: 由于这个问题太长,这是一个总结 我尝试使用IMGURAPI通过跨域XHR更新图像 为了在实现中抽象细节,我使用Jquery表单插件(显然,它包含在fiddle中) 在Chrome、Firefox等浏览器中效果很好,但在IE9中不起作用 预期结果是更新图像并检索图像类型 您仍然可以在下面找到详细信息 谢谢 我有这个HTML: <
- 我尝试使用IMGURAPI通过跨域XHR更新图像
- 为了在实现中抽象细节,我使用Jquery表单插件(显然,它包含在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>
在IE9中,我收到以下错误:
SCRIPT5022: Invalid XML: null
jquery.min.js, line 2 character 10890
XML5619: Incorrect document syntax.
, line 1 character 1
我还使用了Jquery表单插件页面中给出的示例,该页面只使用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>
更新2:
文件:
返回类型:
xml
(功能(){
变量选项={
//目标:'#output1',//要使用服务器响应更新的目标元素
//beforeSubmit:showRequest,//预提交回调
success:afterSuccess,//提交后回调
完成:完成后,
//其他可用选项:
//url:url//重写表单的“操作”属性
键入:'POST'、/'get'或'POST',重写表单的'method'属性
数据类型:'xml'/'xml'、'script'或'json'(预期的服务器响应类型)
//clearForm:true//成功提交后清除所有表单字段
//resetForm:true//成功提交后重置表单
//$.ajax选项也可以在此处使用,例如:
//超时:3000
};
函数过程xml(xml){
变量类型=$(xml).find('type').text();
返回类型;
//查找其他元素并将其添加到文档中
}
函数成功后(responseText、statusText、xhr、$form){
//对于正常的html响应,成功回调的第一个参数
//是XMLHttpRequest对象的responseText属性
//如果向ajaxForm方法传递了数据类型为的Options对象
//属性设置为“xml”,然后是成功回调的第一个参数
//是XMLHttpRequest对象的responseXML属性
//如果向ajaxForm方法传递了数据类型为的Options对象
//属性设置为“json”,然后是成功回调的第一个参数
//是服务器返回的json数据对象
var$xml=process_xml(responseText);
log('success:'+$xml);
}
功能完成后(xhr,状态){
如果(状态='parsererror'){
xmlDoc=null;
//从responseText字符串创建XML文档
if(window.DOMParser){
parser=新的DOMParser();
xml=parser.parseFromString(xhr.responseText,“text/xml”);
}否则{
//Internet Explorer
xml=新的ActiveXObject(“Microsoft.XMLDOM”);
xml.async=“false”;
loadXML(xhr.responseText);
}
}
log('complete:'+process_xml(xhr.responseText));
}
$('#uploadForm').ajaxForm(选项);
})();
提前谢谢。也许可以试试这个?我使用谷歌地图商店定位器。我注意到$.parseXML实际上是在内部实现的,但它是在try/catch中实现的,并且它说您的
数据为null(这很奇怪?)
从jQuery:
<!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>
我以前用过这个插件。如果我还记得这一点,它是使用iframe获取信息,然后读取iframe中的内容。内容存储在属性responseText中。但是IE可能比其他浏览器有更严格的规则。您是否尝试打印出data.responseText的值
如果该值不是XML字符串。我不想这么说,但API不是为Javascript设计的。我学到的是,使用JSONP操作脚本标记是实现跨域XHR的最佳方法。我不认为这个插件能做到
- 演示:
js
代码:
var xml;
if (typeof data == "string") {
xml = new ActiveXObject("Microsoft.XMLDOM");
xml.async = false;
xml.loadXML(data);
} else {
xml = data;
}
// 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和解析XML时是出了名的挑剔。试着这样做:
$(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="" />');
}
});
});
另外,在整个调试过程中使用alert()
,随时提供有关所传递信息的反馈
编辑
关键是要确保XML文件的格式是“良好的”,即它不能包含任何语法错误。您需要以以下内容开始XML文件:
<?
$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;
?>
或者另一种做同样事情的方法是请求一个特定的标题:
<?xml version="1.0"?>
内容类型application/xml
和text/xml
之间的差异很小(它基于每个xml的字符集),但是如果您想知道您可以阅读。我认为非IE部分有问题,因为现在我得到了一个未捕获的异常(无效的xml:[对象文档]),但在IE9中我没有看到任何错误,但是,即使响应主体显示正确的XML文档,它也不会做任何事情。谢谢您的回答。当我试图打印data.responseText时,我在IE9中没有得到任何结果(尽管它在其他浏览器中工作正常),但响应是有效的XML。此外,插件文档页面中的示例在IE9中工作,所以如果这是由
<?
$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;
?>
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) ;
}
});
});
<?xml version="1.0"?>
dataType: ($.browser.msie) ? "text" : "xml",
accepts: {
xml: "text/xml",
text: "text/xml"
}
headers: {Accept: "text/xml"},