How to determine if a Post contains a specific Category in a JSONP feed using jQuery?

爱⌒轻易说出口 提交于 2019-12-13 09:53:50

问题


I need to detect if a post contains a specific category from a JSONP feed. I'm not sure how to read the array as it's currently saying it's null. The link works without any problems though, which is just a string.

$.jsonp({
    url         : "theurl",
    dataType    : "jsonp",
    timeout     : 10000,
    success     : myFunction,
    error       : myErrorFunction
});

function myFunction (data) {
    $.each(data, function(i, post){
        var link = post.permalink,
            hasCategory = $.inArray("specialcategory", post.categories);
    });
}

Here's an example of my JSON:

[
    {
        "id": 1,
        "permalink": "http://domain.com",
        "categories": [
            "category1",
            "specialcategory"
        ]
    }
]

This is the error that appears in Firebug:

can't convert null to object
d()jquery.js (line 16)
a = "specialcategory"
b = undefined
[Break On This Error] (function(a,b){function ci(a){return d...a:a+"px")}}),a.jQuery=a.$=d})(window);

Any help would be greatly appreciated.


回答1:


You might need to check for hasCategory differently - see the jQuery docs:

The $.inArray() method is similar to JavaScript's native .indexOf() method in that it returns -1 when it doesn't find a match. If the first element within the array matches value, $.inArray() returns 0.

Because JavaScript treats 0 as loosely equal to false (i.e. 0 == false, but 0 !== false), if we're checking for the presence of value within array, we need to check if it's not equal to (or greater than) -1.

So the line

hasCategory = $.inArray("specialcategory", post.categories);

should be

hasCategory = $.inArray("specialcategory", post.categories) >= 0;

But it doesn't look like that's your main issue, if myFunction isn't actually receiving the array of data.



来源:https://stackoverflow.com/questions/6117008/how-to-determine-if-a-post-contains-a-specific-category-in-a-jsonp-feed-using-jq

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!