如何使用jQuery确定帖子是否在JSONP提要中包含特定类别? [英] How to determine if a Post contains a specific Category in a JSONP feed using jQuery?

查看:143
本文介绍了如何使用jQuery确定帖子是否在JSONP提要中包含特定类别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要检测帖子是否包含来自JSONP提要的特定类别.我不确定如何读取数组,因为它当前表示为空.该链接可以正常工作,只是一个字符串.

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);
    });
}

这是我的JSON的示例:

Here's an example of my JSON:

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

这是Firebug中出现的错误:

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);

任何帮助将不胜感激.

推荐答案

您可能需要以不同的方式检查hasCategory-请参阅jQuery文档:

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

$.inArray()方法类似于JavaScript的本机.indexOf()方法,在找不到匹配项时返回-1.如果数组中的第一个元素与value匹配,则$.inArray()返回0.

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.

因为JavaScript将0大致等同于false(即0 == false,但0!== false),所以如果我们要检查array中是否存在value,我们需要检查它是否为不等于(或大于)-1.

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.

所以这行

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

应该是

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

但是,如果myFunction实际上没有接收到数据数组,这似乎不是您的主要问题.

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

这篇关于如何使用jQuery确定帖子是否在JSONP提要中包含特定类别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆