开发者

jQuery.ajax: How do I limit the data processed from the remote server?

In the code below, when the input string is "tobacco" (without quotes), the alert function fires in an endless loop of terms. The "terms" are derived from the result set (which is set to 50 to ensure a rich set of data to seed the keywords). However, for some terms, the amount of keywords returned is way too high.

What can I do in the script below to set a max for the number of keywords to process and then proceed once that max has been reached?

    jQuery.ajax({
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        url: "http://boss.yahooapis.com/ysearch/web/v1/"
        +jQuery('#my_keyword').val()+"?"
        +"appid=myID"
        +"&lang=en"
        +"&format=json"
        +"&count=50"
        +"&view=keyterms"
        +"&callback=?", 
        success: function(data)
            {
                var keywords = new Array();
                jQuery.each(data['ysearchresponse']['resultset_web'],
                        function(i,item) 
                            {
                            jQuery.each(item['keyterms']['terms'], 
                            function(i,kw)
                                {
                                key =开发者_开发百科 kw.toLowerCase();
                                alert(key);


I'm not 100% sure I understand the question, but if you just want to limit the number of keywords you iterate through, why not set up a limit counter?

jQuery.ajax({
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    url: "http://boss.yahooapis.com/ysearch/web/v1/"
    +jQuery('#my_keyword').val()+"?"
    +"appid=myID"
    +"&lang=en"
    +"&format=json"
    +"&count=50"
    +"&view=keyterms"
    +"&callback=?", 
    success: function(data)
        {
            var keywords = new Array();
            var keywordsNumber = 0;
            var keywordsMax = 20;
            jQuery.each(data['ysearchresponse']['resultset_web'],
                    function(i,item) 
                        {
                        if (keywordNumber == keywordsMax) { return false; } // Same as 'continue' in a regular loop
                        jQuery.each(item['keyterms']['terms'], 
                        function(i,kw)
                            {
                            key = kw.toLowerCase();
                            keywordsNumber++;
                            alert(key);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜