我是 AJAX 新手,我正在尝试整理一个将可过滤信息从 XML 文档提取到网页的示例。到目前为止,我正在尝试使用这些过滤后的 XML 项目创建一个数组,然后将项目从数组拉到页面上。
我的 XML 文档非常简单,我只想显示“类型”为 100 的项目。在服务器端执行此过滤是最佳实践还是可以在请求期间/之后进行过滤?有谁知道为什么这个脚本不起作用和/或是否有更有效的方法?
这是我的 XML:
<items>
<item id="1">
<type>100</type>
<item>
<item id="2">
<type>101</type>
<item>
<item id="3">
<type>100</type>
<item>
<item id="4">
<type>102</type>
<item>
</items>
这是我的脚本:
$(document).ready(function(){
var array = [];
$.ajax({
type: "GET",
url: "text.xml",
dataType: "xml",
success: function(xml){
$(xml).find("item").each(function(){
if( x == $(this).find("type") == "100"){
$(this).push(array);
}
});
});
$.each(array, function() {
$(body).append("<p>" + $(this).attr("id") + "</p>" );
});
});
最佳答案
尝试
$(document).ready(function(){
$.ajax({
type: "GET",
url: "text.xml",
success: function(xml){
var items = $(xml).find("item").filter(function(){
return $('type', this).text() == '100';
});
items.each(function(index, item){
$('body').append("<p>" + $(item).attr("id") + "</p>" );
});
}
});
});
演示:Plunker
注意:您的 xml 中存在问题,item
的结束标记不正确,应该是</item>
关于jquery - 过滤 AJAX get 请求上的 XML 结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16131703/