同步jquery $ .ajax没有锁定IE?(synchronous jquery $.ajax without locking IE?)

编程入门 行业动态 更新时间:2024-10-26 04:25:05
同步jquery $ .ajax没有锁定IE?(synchronous jquery $.ajax without locking IE?)

花了一点时间试图实现这个并且有一个我觉得在firefox中工作得很好的解决方案,但是当在IE中测试发现使用async:false导致浏览器被锁定(停止响应并且已经冻结)通话时间。

要求基本如下。 我提供了一系列用户可以检查的复选框。 在特定时间,我调用我的函数'selectedSeriesData()',该函数用于向我的服务一个接一个地发送请求以获取所请求的数据。 我特别选择使用sync,以便在执行方法时可以向浏览器输出状态消息和警告。

例如。 “加载数据1/3”,然后“加载数据2/3”,“加载数据3/3”

当然,我现在知道这会锁定某些浏览器,因此IE中的体验不仅会锁定浏览器,而且我尝试显示的任何消息都不会显示。 是否有任何类型的简单doEvents,例如我可以在每次ajax调用之后调用的操作,或者只是重构我的ajax调用的问题。 如果是这样的话,根据我的要求提供任何实施建议?

以下是代码的简化摘录以供参考。

function selectedSeriesData() { var seriesData = []; var index = 0; $.each($("input[name='idCheckBox']:checked"), function () { var id = $(this).val(); $("#loadingMessage").text("Loading " + id + "..."); $.ajax({ type: 'POST', async: false, url: '<%: loadSeriesDataPath %>', dataType: 'json', data: { Id: id }, success: function (data) { seriesData[index] = data; index++; }, error: function (xhr, ajaxOptions, error) { $("#warnings ul").append('<li>A communication error occured while attempting to load data for the series.</li>'); } }); } }); return seriesData; }

Spent a bit of time trying to achieve this and have a solution that I think works very well in firefox, but when testing in IE discovered that using async: false cause the browser to be locked (stops responding and apprears to have frozen) for the duration of the call.

Requirement basically as follows. I supply a series of check boxes which users may check. At a particular time I call my function 'selectedSeriesData()' which is used send requests to my service one after another getting the requested data. I specificly chose to use sync so that I could output status messages and warnings to the browser while the method is executing.

eg. "Loading data 1/3", then "Loading data 2/3", "Loading data 3/3"

Of course, I now know that this locks certain browsers so the experience in IE not only locks the browser but any messages I tried to display never got shown. Is there any sort of simple doEvents like action I can call after each ajax call has been made, or is it just a matter of restructuring my ajax calls. If that's the case, any implementation advice given my requirement?

Below is a simplified extract of code for reference.

function selectedSeriesData() { var seriesData = []; var index = 0; $.each($("input[name='idCheckBox']:checked"), function () { var id = $(this).val(); $("#loadingMessage").text("Loading " + id + "..."); $.ajax({ type: 'POST', async: false, url: '<%: loadSeriesDataPath %>', dataType: 'json', data: { Id: id }, success: function (data) { seriesData[index] = data; index++; }, error: function (xhr, ajaxOptions, error) { $("#warnings ul").append('<li>A communication error occured while attempting to load data for the series.</li>'); } }); } }); return seriesData; }

最满意答案

您可以使用jQuery Deferred对象继续使用异步请求,然后在所有结果完成后“加入”结果。

function selectedSeriesData(cb) { var reqs = []; $("#loadingMessage").text("Loading..."); $("input[name='idCheckBox']:checked").each(function () { var id = $(this).val(); var req = $.ajax({ type: 'POST', url: '<%: loadSeriesDataPath %>', dataType: 'json', data: { Id: id }, error: function(xhr, ajaxOptions, error) { $("#warnings ul").append('<li>A communication error occured while attempting to load data for the series.</li>'); } }); reqs.push(req); }); $.when(reqs).done(function() { cb($.makeArray(arguments)); }); }

现在您只需将回调传递给您的函数,然后只要所有结果都成功完成,它就会收到一个包含AJAX请求所有结果的数组。

注意: $.when上的文档并不是很清楚它是否接受包含延迟的单个数组。 万一它不起作用尝试$.when.apply($, reqs)而不是$.when.apply($, reqs) $.when(reqs)

I think the best answer to my question is... you're doing it wrong. I didn't have any luck with $.when as was suggested (perhaps it was due to my understanding of it), so came up with the following answer myself.

Basically, use callbacks to implement a sort of recursive queuing. This may sound obvious to all you guys, but its new to me, and I think the experienced jqueryer out there would agree with my implementation (please let me know if I'm doing it right!)

Firstly, instead of looping through my checkboxes and making ajax requests, build up an array of requests. This gets rid of the need to return my results from the original method and begins a chain of method execution evetually leading to the desired result.

function selectedSeriesData() { var requests = []; $.each($("input[name='somethingCheckBox']:checked"), function () { var id = $(this).attr('value'); var request = { id: id }; requests.push(request); }); loadRequests(requests); }

From the array of requests, start call loadRequests which initializes a recursive callback implementation to load data from my service.

function loadRequests(requests) { $("#loader").show(); var seriesData = []; loadRequestAt(requests, 0, seriesData); }

the recursive method called is loadRequestAt, which keeps track of the array of requests, a specific index to load this itteration, and seriesData that is added to as the method is called. Anon methods Success used to build up my seriesData, Error used to report errors, and Complete most importantly used to begin the next itteration of requests or if all requests have been made, render results to the screen.

function loadRequestAt(requests, loadAtIndex, seriesData) { var currentRequest = requests[loadAtIndex]; $("#loadingMessage").text("Loading " + currentRequest.id + "..."); $.ajax({ type: 'POST', url: '<%: loadSeriesDataPath %>', dataType: 'json', data: { Id: currentRequest.id }, success: function(data) { seriesData.push(data); }, error: function(xhr, ajaxOptions, error) { $("#warnings ul").append('<li>A communication error occured while attempting to load ' + currentRequest.id'.</li>'); }, complete: function() { var nextIndex = loadAtIndex + 1; if (nextIndex < requests.length) { loadRequestAt(requests, nextIndex, seriesData); } else { $("#loader").hide(); renderResults(seriesData); } } }); }

Important lessons learned. Do use Asynchronous calls when using AJAX (Asynchronous JavaScript and XML). Do make use of anonymous callback methods provided to implement progressive queueing functionality (I'm sure there is an accepted name for this but I'm not sure of it). Hope my steps in learning helps others who are new to jquery and ajax calls. Thanks!

更多推荐

本文发布于:2023-08-08 00:36:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1466737.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:ajax   jquery   locking   synchronous

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!