【问题标题】:Jquery .find works with xml but not JSONJquery .find 适用于 xml 但不适用于 JSON
【发布时间】:2013-01-04 16:20:57
【问题描述】:

这适用于 XML

$(document).ready(function() {
            $.ajax({
                type: "GET",
                url: "http://api.soundcloud.com/users/123/playlists.xml?client_id=ID",
                dataType: "xml",
                success: parse
            });
        });

        function parse(xml) {
           $(xml).find("playlists").each(function(){
                        //var title = $(this).find('title').text();
                        $("#catTitle").append($(this).text()+ "<br />"); 
                    });
        } 
        ​

但是当我把它改成这个时,它就不起作用了。我在$(json).find("playlists").each(function(){ 之后放了一个 alert() 并且它永远不会被调用。有什么想法吗?

$(document).ready(function() {
        $.ajax({
            type: "GET",
            url: "http://api.soundcloud.com/users/123/playlists.json?client_id=ID",
            dataType: "json",
            success: parse
        });
    });

    function parse(json) {
       $(json).find("playlists").each(function(){
                    //var title = $(this).find('title').text();
                    $("#catTitle").append($(this).text()+ "<br />"); 
                });
    } 
​

【问题讨论】:

  • 你不能用jQuery搜索json,它是一个javascript对象或数组。像 javascript 对象或数组一样使用它。
  • 是的,我有一个想法,您为什么希望它起作用?它也不是针对 XML 的,只是碰巧 XML 有足够的类似于 HTML 的结构来欺骗 JQuery
  • json 未格式化为与使用标签的 .find() 方法一起使用

标签: xml json jquery


【解决方案1】:

这不是 jQuery 设计的目的。如果要使用 JSON 定义的对象或数组,请直接使用该对象或数组。

【讨论】:

【解决方案2】:

试试这个:

function parse(json) {
   $.each(json.playlists,function(idx,el){
       $("#catTitle").append(el+ "<br />"); 
   });
}

【讨论】:

  • 谢谢 - 这就是我最终做的事情var items = []; var content = null; $.getJSON('http://api.soundcloud.com/users/123/playlists.json?client_id=[Client ID]',function(data) { content = data; }); function parse(json) { $.each(content, function (index, item) { if (item.genre == type){ //rest of function here } } };
猜你喜欢
  • 2013-03-24
  • 2012-05-27
  • 2020-10-08
  • 2015-01-16
  • 1970-01-01
  • 1970-01-01
  • 2012-08-01
  • 2021-06-22
  • 2011-08-21
相关资源
最近更新 更多