我正在尝试学习JQuery - 我对ajax有一个小问题.我正在尝试使用页面的XML响应返回的值填充javascript数组.
这是我的主页(ajax.html):
<html>
<head>
<script type="text/javascript" src="jquery/jquery.js"></script>
<script type="text/javascript" src="jquery/fiber.js"></script>
</head>
<body>
<p>Ajax</p>
<script>
var ringType = new Array();
</script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
fiber.js是这样的:
//process things for fiber map
jQuery(document).ready(function() {
// do stuff when DOM is ready
//populate and display ringType
$.ajax({
type: "GET",
url: "ajaxHelper.pl",
data: {
getRingTypes: "1",
},
dataType: "xml",
success: function(xml) {
//if the query was successfull,
alert("Got an xml object:"+$(xml));
$(xml).find("ringType").each( function(){
alert("Received reply "+$(this).text());
var type = $(this).html(); //save the value
//append to ringType array
ringType.push(type);
});
},
error:function (xhr, ajaxOptions, thrownError){
alert(xhr.status);
alert(thrownError);
}
});
for(var i=0; i<ringType.length; i++){
document.write("<br>"+ringType[i]);
}
});
Run Code Online (Sandbox Code Playgroud)
ajaxHelper.pl生成此XML(在\?中没有反斜杠)(作为content-type text/xml):
<?xml version="1.0" encoding="ISO-8859-1"?>
<\?xml version="1.0" encoding="ISO-8859-1"\?>
<ringType>IA</ringType>
<ringType>IL</ringType>
<ringType>IN</ringType>
<ringType>IR</ringType>
<ringType>RT</ringType>
Run Code Online (Sandbox Code Playgroud)
问题是,每次加载ajax.html时,ajax查询都成功,但执行错误函数!xhr.status = 200(意味着查询没问题)并且thrownException未定义.
通过http://groups.google.com/group/jquery-en/browse_thread/thread/23679594ebe128a9
服务器可以返回带有200状态代码的XML文档.但是如果浏览器无法解析文档,则会发生parseerror并且将调用jQuery的错误处理程序.
确保你返回有效的xml :)
所有浏览器都会出现这种情况吗?
1)可以使用complete代替success和error来处理状态。使用 if 检查 XHR 返回状态并进行相应的分支。
http://docs.jquery.com/Ajax/jQuery.ajax#options