beg*_*ner 0 xml asp.net jquery xmlhttprequest xml-serialization
XML
<?xml version='1.0' encoding='utf-8' ?>
<RecentTutorials>
<Tutorial author='The Reddest'>
<Title>Silverlight and the Netflix API</Title>
<Categories>
<Category>Tutorials</Category>
<Category>Silverlight 2.0</Category>
<Category>Silverlight</Category>
<Category>C#</Category>
<Category>XAML</Category>
</Categories>
<Date>1/13/2009</Date>
</Tutorial>
</RecentTutorials>
Run Code Online (Sandbox Code Playgroud)
脚本
$.ajax({
type: "post",
url: "Default.aspx?cmd=Setting",
success: parseXml
});
Run Code Online (Sandbox Code Playgroud)
alert(xml);//show xml File Success
$(xml).find("Tutorial").each(function()
{
$("#b").append($(this).attr("author") );
}
没有读取的XML文件虽然是alert(xml); 显示XML文件
而不是$(),用于$.parseXML解析XML字符串.(更新:请参阅下面的注释,parseXML已添加到jQuery 1.5中,但如果需要,可以很容易地将其添加到旧版本.)它将为您提供原始XML文档; 然后你用$()它来获取该doc的jQuery包装器.
像这样:
var xml =
"<?xml version='1.0' encoding='utf-8' ?>" +
"<RecentTutorials>" +
"<Tutorial author='The Reddest'>" +
"<Title>Silverlight and the Netflix API</Title>" +
"<Categories>" +
"<Category>Tutorials</Category>" +
"<Category>Silverlight 2.0</Category>" +
"<Category>Silverlight</Category>" +
"<Category>C#</Category>" +
"<Category>XAML</Category>" +
"</Categories>" +
"<Date>1/13/2009</Date>" +
"</Tutorial>" +
"</RecentTutorials>";
$($.parseXML(xml)).find("Tutorial").each(function() {
var author = $(this).attr("author");
});
Run Code Online (Sandbox Code Playgroud)
如果你正在加载XML ajax,你通常不需要这样做,因为jQuery将为你做这个加载序列的一部分,然后给你XML文档作为回调的data参数success,但如果你只是一个任意的字符串,你想要解析它,parseXML是工作的工具.
ajax 例:
$.ajax({
url: "the/url/to/load/the/xml/from",
method: "GET",
dataType: "xml",
success: function(data) {
var xdoc = $(data); // Note that jQuery has already done the parsing for us
display("Getting tutorials");
var tutorials = xdoc.find("Tutorial");
display("Found: " + tutorials.length);
tutorials.each(function() {
display("Tutoral author: " + $(this).attr("author"));
});
},
error: function(jxhr, status, err) {
display("Ajax error: status = " + status + ", err = " + err);
}
});
Run Code Online (Sandbox Code Playgroud)
更新:parseXML已添加到v1.5中的jQuery.如果可以,请升级到最新版本以使用它.如果不能,如果必须使用过时的版本,则可以轻松地将该功能添加到您自己的脚本中.与jQuery的许多部分不同,它在jQuery源代码中非常自包含:
jQuery.parseXML = function( data , xml , tmp ) {
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 );
}
tmp = xml.documentElement;
if ( ! tmp || ! tmp.nodeName || tmp.nodeName === "parsererror" ) {
jQuery.error( "Invalid XML: " + data );
}
return xml;
};
Run Code Online (Sandbox Code Playgroud)
这是我的第一个示例的实时副本,但使用jQuery 1.4.4以及上面的内容.
| 归档时间: |
|
| 查看次数: |
2529 次 |
| 最近记录: |