Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
183 views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...