如何处理在他们reqested顺序的jQuery Ajax请求如何处理、顺序、Ajax、reqested

2023-09-11 00:35:10 作者:好菇凉走到哪里都是阳光

我在做一个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.

这是我使用的请求code:

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).

例如,假设你有一个容器像&LT; D​​IV ID =容器&GT;&LT; / DIV&GT; ,你可以执行以下操作:

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.)