我正在对一个返回一些xml的jsp页面进行ajax调用。一切似乎都很好,当我使用警报显示返回的数据时,一切看起来都很好。但是,当我尝试在jQuery中解析xml时,我无法做到。
返回的xml如下所示:
<?xml version="1.0" encoding="ISO-8859-1"?>
<locations>
<location>
<branch>Branch</branch>
<branchid>BranchID</branchid>
<phone>Phone</phone>
<address>Address</address>
<phone2>Phone2</phone2>
</location>
</locations>
我的ajax看起来像这样:
$.ajax({
type: "POST",
url: "test.jsp",
data: {zc : $('#zc').val()},
async: false,
success: function(message){
message = message.trim();
$(message).find('location').each(function(){
var branch = $(this).find('branch').text();
alert(branch);
})
}
})
答案 0 :(得分:0)
示例是:
var xml = "<music><album>Beethoven</album></music>";
var result = $(xml).find("album").text();
For more in-depth information, read the tutorial Easy XML Consumption using jQuery
首先获取“位置”标记:
$(message).find('locations').find('location')
答案 1 :(得分:0)
使用jQuery.parseXML
var xml = "<rss version='2.0'><channel><title>RSS Title</title></channel></rss>",
xmlDoc = $.parseXML( xml ),
$xml = $( xmlDoc ),
$title = $xml.find( "title" );
供参考:jQuery parseXML
答案 2 :(得分:0)
请尝试下一个代码:
var message = "<?xml version='1.0' encoding='ISO-8859-1'?>"
+"<locations>"
+"<location>"
+"<branch>Branch</branch>"
+"<branchid>BranchID</branchid>"
+"<phone>Phone</phone>"
+"<address>Address</address>"
+"<phone2>Phone2</phone2>"
+"</location>"
+"</locations>";
$('location', message).each(function(xml){
console.log( 'branch:' +$(this).find('phone2').text());
console.log( 'branchid:' +$(this).find('branchid').text());
console.log( 'phone:' +$(this).find('phone').text());
console.log( 'address:' +$(this).find('address').text());
})