简体   繁体   English

JavaScript / jQuery解析xml

[英]JavaScript / jQuery parse xml

I wanted to get like count numbers from this link 我想从此链接中获取计数数字

http://api.facebook.com/restserver.php?method=links.getStats&urls=http://www.apple.com

var xml = "http://api.facebook.com/restserver.php?method=links.getStats&urls=http://www.apple.com;"
var xmlDoc = $.parseXML(xml),
$xml = $(xmlDoc),
$title = $xml.find( "like_count" );
$('.countnumber').text($title.text());

however, I got this error 但是,我得到了这个错误

Uncaught Error: Invalid XML: http://api.facebook.com/restserver.php?method=links.getStats&urls=http://www.apple.com ; 未捕获的错误:无效的XML: http ://api.facebook.com/restserver.php?method=links.getStats&urls= http : //www.apple.com ;

Is there a way to parse it by javascript? 有没有办法通过javascript解析它?

Thanks 谢谢

In your case xml contains a resource url, not a xml string that is the cause of the error. 在您的情况下, xml包含资源URL,而不是导致错误的xml字符串。 You need to read the contents of the url first then parse it. 您需要先阅读url的内容,然后解析它。

You need to read the contents of the URL 您需要阅读URL的内容

var xml = "http://api.facebook.com/restserver.php?method=links.getStats&urls=http://www.apple.com;"
$.get(xml).done(function(xml){
    var $xml = $(xml),
        $title = $xml.find( "like_count" );
    console.log($title.text())
})

Demo: Fiddle 演示: 小提琴

As mentioned in the comments retrieve your xml first. 如注释中所述,首先检索您的xml。

$.ajax({
    url: "http://api.facebook.com/restserver.php?method=links.getStats&urls=http://www.apple.com;",
    dataType: "xml"
}).done(function(data) {
    var $xml = $(data),
        $title = $xml.find("like_count");
    $('.countnumber').text($title.text());
});

You need a string representing your xml, not the URI to the resource. 您需要一个表示xml的字符串,而不是资源的URI。 Also, parseXML isn't even neccessary. 另外,甚至parseXML

You need to use AJAX to get the XML: 您需要使用AJAX来获取XML:

    var xml = "http://api.facebook.com/restserver.php?       method=links.getStats&urls=http://www.apple.com;";

    $.get(xml, function(data){
      var xmlDoc = $(data);
      .. your code here
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM