Possible to make AJAX call that doesn't return?

前端 未结 4 1636
忘掉有多难
忘掉有多难 2020-12-30 11:57

Is it possible to send an jQuery.ajax call or equivalent without any sort of response? I want to trigger something on the server as I leave the page with the onbeforeunload

相关标签:
4条回答
  • 2020-12-30 12:36

    Assuming you're using something like this:

    $.ajax({
       url: "test.html",
       context: document.body
    })
    

    (borrowed from http://api.jquery.com/jQuery.ajax/ and edited), you can discard the response.

    0 讨论(0)
  • 2020-12-30 12:45

    You could use the navigator sendBeacon API mentioned referenced in this stack overflow answer or directly linked to here.

    From the description on the site, it asynchronously sends off some data and just checks if it was able to queue the data for sending or not. The unload handler shouldn't ignore the request like it might do with other asynchronous XMLHttpRequests.

    navigator.sendBeacon(url, data) - The sendBeacon() method returns true if the user agent is able to successfully queue the data for transfer, Otherwise it returns false.

    ...

    ensuring that the data has been sent during the unloading of a document is something that has traditionally been difficult for developers, because user agents typically ignore asynchronous XMLHttpRequests made in an unload handler.

    0 讨论(0)
  • 2020-12-30 12:53

    Every request has a response. Even if the server throws an error a response is coming back with the error.

    You can ignore the response if you like to just don't add a success callback.

    $.ajax({
        url: "theURL",
        data: theData
    });
    
    0 讨论(0)
  • 2020-12-30 12:55

    If you are trying to return a response as soon as possible I think that is more of a server architecture decision. You can offload the actual work the request involves to a broker or something so you can return to the user as soon as possible? I don't think sending just a one way message is feasible

    0 讨论(0)
提交回复
热议问题