【问题标题】:check for null response using getJson method使用 getJson 方法检查空响应
【发布时间】:2013-01-11 22:07:48
【问题描述】:

刚刚完成一个应用程序,我需要在 json 方面再实现一件事。

我有一个 jquery 自动完成,它使用我编写的返回 json 的 Web 服务。

我需要稍微改变一下,这样如果第一个带有参数的请求返回 null,那么它会使用不带参数的默认 url 再次尝试进行主搜索。

只是为了确保我没有遗漏任何技巧,我说过我会问,看看是否有任何 jquery 大师有一种优雅的方式来实现这一点。

var cache = {},lastXhr;
var web_service_url_default = "http://json_sample.php";
var web_service_url_specific = "http://json_sample.php/?param1=hello&param2=world";

var autocomp_opt = {
        minLength: 1,
        source: function( request, response ) {
            var term = request.term;
            if ( term in cache ) {
                response( cache[ term ] );
                return;
            }

            lastXhr = $.getJSON( web_service_url_specific, request, function( data, status, xhr ) {
                cache[ term ] = data;
                if ( xhr === lastXhr ) {
                    response( data );
                }
            });
        }
};

这是我的自动完成选项变量,它输入到自动完成调用中,如下所示,并且工作正常。

$('.some_class').autocomplete(autocomp_opt);

我需要更改它,以便如果第一个请求返回空,那么它会触发没有参数的默认请求。

一如既往地为帮助喝彩。


更新了工作示例

搞定了,看看下面的代码,以防它帮助任何人。它可能不是最优雅的,但它仍然有效。

请注意,在此示例和测试中,缓存似乎并没有很好地发挥作用,并导致请求不时被触发,因此我将其删除。现在它可以 100% 运行。

var autocomp_opt = {
            minLength: 1,
            source: function( request, response ) {
                var term = request.term;

                lastXhr = $.getJSON( web_service_url_specific, request, function( data, status, xhr ) {
// check if there is only one entry in the json response and if the value is null, my json script returns empty like this
                        if(data.length == 1 && data[0].value == null){
                            $.getJSON( $web_service_url_default, request, function( data, status, xhr ) {
                                response( data );
                            });
                        }else{
                            response( data );
                        }
                });
            }
        };

$('.some_class').autocomplete(autocomp_opt);

【问题讨论】:

  • 我很确定if ( xhr === lastXhr ) 永远不会是真的。
  • 确实,这直接来自 jquery-ui 站点示例,所以在他们的缓存示例下。我自己也考虑过。实际上,我自己也完成了这项工作,并且也考虑了您对 xhr 的建议。感谢您的提醒。

标签: jquery json jquery-ui autocomplete


【解决方案1】:
if(data.length == 1 && data[0].value == null) 
{
    ...
}

我设法让这个自己工作。如果对任何人有帮助,请参阅上面的示例。这可能不是最优雅的方法,但它仍然有效。 干杯。

【讨论】:

  • 你应该在你的答案中发布你的完整解决方案,而不是你的问题。
【解决方案2】:

我假设“空请求返回”意味着请求失败(例如错误,不是空字符串等)。您可以使用 $.ajax 构建您的 ajax 调用并挂钩到错误函数:

$.ajax({
  url: web_service_url_specific,
  data: request,
  dataType, 'json',
  success: function( data, status, xhr ) {
    // not going to question this part
    cache[ term ] = data;
    if ( xhr === lastXhr ) { response( data ); }
  },
  error: function() {
    // fallback ajax call
    $.ajax({});
  }
});

【讨论】:

    猜你喜欢
    • 2015-10-09
    • 1970-01-01
    • 1970-01-01
    • 2020-01-16
    • 1970-01-01
    • 2023-03-24
    • 1970-01-01
    • 2011-02-05
    • 2011-03-15
    相关资源
    最近更新 更多