简体   繁体   中英

Long polling with ajax and servlets

I'm doing a project using javascript for client side and servlets for server side. I'm trying to implement a way to update client info real time. ie when a client update some info in the web application, other clients will also see the update. I found that long polling is a good technique for this. This is the code I tried to get to work.

function poll() {
        setTimeout(function() {
        $.ajax({ 
            type: "GET",
            url: "server",
            contentType: "application/json", 
            data: {
                type: "update",
                card: "string"
            },
            success: function(data) {
                alert(data);
            },
            error: function(data) {
                alert('eroor');
            },
            dataType: "json", 
            complete: poll });
        }, 5000);
} 

I'm trying to send a request to the server every 5 seconds and get the response with new updates. But in all the skeleton codes I saw in the web, data: is not set. Without setting it, how would the sever know the type of request it received since there are other types of requests too. But when I set data: no requests are sent from the client. But without setting data: requests are sent to the server. Is it wrong to set data: ? Without it how would I let the servlet know the type of the request?

I understand that like mentioned in here long polling is not what I'm trying to do. But can anyone explain what I should do and where I'm doing wrong.

Since you make a GET request, the data values are appended to the URL as URL parameters. Your servlet must then use request.getParameter("type") and request.getParameter("card") to extract the information from the request.

If you think that no request is sent, first check your console for errors and look at the net communications panel in the developer tools of your browser.

data:

issue is how you set the data. If you want to send json object, you have to stringify before you send it, like below.

$.ajax({
  url: url,
  type: "POST",
  data: JSON.stringify(data),
  contentType: "application/json",
  complete: callback
});

Without it how would I let the servlet know the type of the request?

What you mean by this? to know the contentType? If so, send contentType parameter as above.

I understand that like mentioned in here long polling is not what I'm trying to do. But can anyone explain what I should do and where I'm doing wrong.

Yes. This is not exactly a long polling. This is how you send a request to the server in every 5 seconds. Anyway server should support to long polling.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM