如何按请求的顺序处理jquery ajax请求 [英] How to process jquery ajax requests in the order they were requested

查看:113
本文介绍了如何按请求的顺序处理jquery ajax请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个java servlet页面,它检查域名列表,并通过jquery ajax请求检查每个域名。它工作正常,除了结果不按顺序附加到DOM。在请求的顺序中处理请求的最佳方法是什么,但也像长轮询效果一样异步。我是javascript的新手。

I am making a java servlet page that checks a list of domain names and it checking each name through a jquery ajax request. It works fine except the results are being appended to the DOM out of order. What is the best method to process requests in the requested order but also be asynchronously like a long polling effect. I am new with javascript.

这是我用于请求的代码:

This is the code I am using for the requests:

$.ajax({
    async:true,
    type:'GET',
    url:servlet,
    success:function(data){
        $('p').append(data+"<br>");
    }, 
}); 

我正在考虑向java servlet发送一个序列号,它将通过JSON返回它,但我是想知道是否有更简单的方法。

I was thinking of sending a sequence number to the java servlet which would return it through JSON but I was wondering if there was a simpler way.

推荐答案

我要做的是提前为响应创建容器然后绑定它周围的回调(实际上没有像bind()函数那样绑定)。

What I would do is create the containers for the response ahead of time and then bind the callback around it (not actually binding as in the bind() function).

例如,假设你有一个类似的容器< div id =container>< / div> ,您可以执行以下操作:

For example, assuming you have a container something like <div id="container"></div>, you can do the following:

function makeRequest(something) {
    var target = $("<div></div>");
    $("#container").append(target);
    $.get("", {something: something}, function(data) {
        target.html(data);
    });
}

这在灵活性方面是一个相当糟糕的例子,但它应该说明一点。它在发出请求之前向容器添加div,然后使用该div将响应推送到。这意味着div将按请求的顺序附加。你可以扩展这个想法,使它看起来像div在它们填充之前不存在,或者你可以在其中加载加载消息。

It's a rather bad example in terms of flexibility, but it should illustrate the point. It adds a div to the container before the request is made and then uses that div to push the response into. That means that the divs will be appended in the order the requests are made. You could extend this idea to use styling to make it look like the divs aren't there until they're populated, or you could have a "Loading" message in them.

(另外,使用某些参数传递的数据相当糟糕,但希望你明白这一点。)

(Also, the data passing is rather bad with the something parameter, but hopefully you get the point.)

这篇关于如何按请求的顺序处理jquery ajax请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆