gpt4 book ai didi

javascript - ajax 速度 - 简化多个 ajax 调用

转载 作者:行者123 更新时间:2023-11-30 12:44:31 25 4
gpt4 key购买 nike

我的网站上有一个搜索过滤器,当用户取消选中某个框时,会向服务器发送一个 ajax 调用,返回新的、缩小的搜索结果。

但是现在,用户可以同时取消选中大约 20 个框,这迫使我进行 20 个不同的 ajax 调用——这非常慢

关于如何将 20 个不同的 ajax 调用传递到一个以加快速度的任何想法?

这是我的代码:

// to allow us to process the "only" buttons, which don't register the click event we're looking for
$("input[type=checkbox]").change(function() {

// remove the original, unfiltered results
$('#original_results').css("display", "none");

// which filter section does the filter belong to
var filter_section = $(this).attr('name');

// should it be filtered out or left in
var remove = $(this).prop('checked');

// if needs to be filtered
if (!remove)
{
// add it to our filter list for the specified section
filters[filter_section].push(this.value);
}
else
{
// take it off the list for the specified section
var index = filters[filter_section].indexOf(this.value);
if (index > -1)
{
filters[filter_section].splice(index, 1);
}
}
doAjax();
});

// ajax function

function doAjax() {
// get slider values
var ranges = $('#pay_range').slider('values');
// define data to post
var data = {
min: ranges[0],
max: ranges[1],
filters: filters,
criteria: criteria
};
// post data



$.ajax({
type: 'POST',
url: '/results/search_filter',
data: data,
beforeSend: function() {
$('#search_results').html('Updating your query');
},
success: function(response) {
$('#search_results').html(response);
},
dataType: "html"

});


}

最佳答案

据我了解,您希望每个操作只调用一次 AJAX,即使该操作包括更改多个复选框也是如此。

我已经通过使用 javascript 的 setTimeout() 来“缓冲”事件来实现这一点。更改复选框时,会设置一个短超时,这将触发 AJAX。如果在该时间段内更改了另一个复选框,则将重新设置超时(而不是触发 AJAX 两次)。 AJAX 仅在超时结束时触发一次。

// initialize timer variable
var ajaxtimer;

// function to run AJAX
function runajax() {
alert('ajax');
}

// clicking a checkbox sets all checkboxes to the same state
$("input[type=checkbox]").on('click', function () {
$('input[type=checkbox]').prop('checked', this.checked).change();
});

// fires on checkbox change, sets short timeout
$("input[type=checkbox]").on('change', function () {
clearTimeout(ajaxtimer);
ajaxtimer = setTimeout(runajax, 50);
});

WORKING EXAMPLE (jsfiddle)

编辑:

我看到您发布的链接并进行了以下调整:

我在文件的顶部定义了这个变量:

var ajaxtimer;

在results.js的第156行,我改了:

doAjax();

clearTimeout(ajaxtimer);
ajaxtimer=setTimeout(doAjax,50);

Here's a jsfiddle .布局被砍掉了,但您可以看到单击“唯一”链接只会导致一次 ajax 调用,而不是对每个更改的复选框进行一次调用。

关于javascript - ajax 速度 - 简化多个 ajax 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23070853/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com