jir*_*iya 6 jquery json jquery-ui autocomplete
刚刚完成一个应用程序,我需要在json方面实现一件事.
我有一个jquery auto complete,它使用我写的一个返回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¶m2=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 );
}
});
}
};
Run Code Online (Sandbox Code Playgroud)
这是我自动完成的选项变量,它输入到自动完成调用,如下所示,并且工作正常.
$('.some_class').autocomplete(autocomp_opt);
Run Code Online (Sandbox Code Playgroud)
我需要改变它,以便如果第一个请求返回空,那么它将触发没有参数的默认请求.
一如既往的干杯.
更新了工作示例
完成后,请参阅以下代码,以防它对任何人有帮助.它可能不是最优雅但它无论如何都有效.
请注意,在此示例中并且在测试中,缓存似乎不太好并且导致请求不会一次又一次地被触发,因此我将其删除.现在它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);
Run Code Online (Sandbox Code Playgroud)
if(data.length == 1 && data[0].value == null)
{
...
}
Run Code Online (Sandbox Code Playgroud)
我自己设法让这个工作起来。如果对任何人有帮助,请参阅上面的示例。这可能不是最优雅的方式,但它仍然有效。干杯。
| 归档时间: |
|
| 查看次数: |
2998 次 |
| 最近记录: |