jquery ajax GET request executing twice

泪湿孤枕 提交于 2020-01-12 11:58:08

问题


I have the following ajax request that is executed at a click of a button:

<a href="javascript:test()"><img src="css/images/test.png"></a>

function test(){
    console.debug("*");

    $.ajax({
        type: "GET",
        dataType: "json",
        url: '/path/to/url',
        success: function(data){
            console.debug("**");
        }, 
        error: function(jqXHR, status, error){
            console.debug("*** " + status + " : " + error + " : " + jqXHR.status);
        },
        cache: false
    });
}

The request response takes approximately 30 seconds to return. However, the request is received and executed by the server twice as can be seen by the apache logs. The timestamp of the requests are 30 seconds apart but the request is identical (e.g ?_=1363692320782). The click response function is called once and the error callback is invoked once (exactly 60 seconds after initial request), although the apache response is a 200.

This problem has been reproduced in a Samsung Galaxy S2, android version 2.3.5 in a phonegap application.

UPDATE - adding Apache log entries from comment below

1.2.3.4 - - [19/Mar/2013:14:07:59 +0000] "GET /pcapi/records/dropbox/08342hjg9gpqm7g/?_=1363702072225 HTTP/1.1" 200 11139 "-" "Mozilla/5.0 (Linux; U; Android 2.3.5; en-gb; GT-I9100 Build/GINGERBREAD) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1"
1.2.3.4 - - [19/Mar/2013:14:08:29 +0000] "GET /pcapi/records/dropbox/08342hjg9gpqm7g/?_=1363702072225 HTTP/1.1" 200 11139 "-" "Mozilla/5.0 (Linux; U; Android 2.3.5; en-gb; GT-I9100 Build/GINGERBREAD) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1"

UPDATE - adb logcat

I/Web Console(16747): * at file:///android_asset/www/js/mobile.js:1769
I/Web Console(16747): *** error : : 0 at file:///android_asset/www/js/mobile.js:1779

UPDATE - TCP/IP monitor

Putting the requests through a TCP/IP monitor shows both requests being sent with a 200 response for both.


回答1:


I hit this exact problem with my app running on Android 2.3.5. I could only conclude that the webview was retrying the request after a timeout. I could find no way to affect the duration of the timeout.

In the end, I rewrote the code such that the initial request spun off an asynch process on the server and returned immediately. Then, from a setTimer on the page, I would check the status of the server process (again, returning immediately). When the status was "complete", the page would move along to the next step.

I hope that helps. I certainly understand your frustration with this. I spent a couple of days myself fighting with it.

Edit: This may have been the article that sent me in the direction of an asynchronous solution. I believe the problem stated here is one and the same:

XmlHttpRequest double posting issue in Android




回答2:


If your URL path defined here url: '/path/to/url' is to a folder and not a specific file try adding a trailing slash like this url: '/path/to/url/'.

What happens when a file is not specified is that the Apache web server sends a 301 redirect to the AJAX client with a new URL (with the trailing slash), so the client issues a new request to the proper URL.

See a similar question posted here: jQuery $.ajax() executed twice?

See the Apache doc reference here: http://httpd.apache.org/docs/2.0/mod/mod_dir.html#directoryslash




回答3:


What about using beforeSend: and complete: AND .ajaxSend() + ajaxSuccess(), also try with cache: true

$(document).ajaxSend(function (event, jqxhr, settings) {
    console.log("triggered ajaxSend !");

    if ( submission_active == true ) {
        jqxhr.abort();
    }

    submission_active = true;
});

$(document).ajaxSuccess(function (event, xhr, settings) {
    console.log("triggered ajaxSuccess !");
    submission_active = false;
});

$.ajax({
    type: "GET",
    dataType: "json",
    timeout: 30000,
    cache: false,
    url: '/path/to/url',
    success: function(data){
        console.debug("**");
    }, 
    beforeSend: function(xhr, opts){
        if(submission_active == true){
            xhr.abort();
        }

        submission_active = true;
    },
    complete: function(){
        submission_active = false;
    }
    error: function(jqXHR, status, error){
        console.debug("*** " + status + " : " + error);
    }
});



回答4:


Click event is being triggered twice. The below code fixes this issue.

$('.selector').unbind('click').bind('click', function () {
 //...
 // Ajax code
 //...
});



回答5:


I've tried this one in my mobile site developing the only problem was in my form and then on my javascript I declared

$("#button_submit").onclick(function(){
   //ajax request here
});

and also dont forget to remove the form attributes like action and method if you're using ajax

I hope it helps you ^_^




回答6:


 <a href="javascript:test()">

thats your issue. If you are going to use jquery, use their css selectors!!!!!!!! that href:javascript stuff is buggy across browsers/devices .




回答7:


Sounds more like a problem with event propagation. I was seeing similar symptoms (albeit on ios) and it came down to the 'touchstart' and 'touchend' events both firing the 'click' event. Have you tried something like this:

$("a").click(function (e) {
    e.preventDefault();
    alert('Clicked');
    test();
});

Hope this helps!
Cheers
JD




回答8:


The issue you are facing is commonly called "bouncing" it's also faced with switches in electronics, when you are pressing and releasing a button the switch is triggered twice, so you need to either set a delay for the function or unbind it once you are done with your click.

You could use Ben Alman's throttle script to debounce your clicks, it's very useful in preventing multiple ajax calls from taking place, combine that with a delay and your issue should be fixed

http://benalman.com/code/projects/jquery-throttle-debounce/examples/debounce/

            var debounceClick = $.debounce(test, 1000);
            function test() {
                console.debug("*");
                $.ajax({
                    type: "GET",
                    dataType: "json",
                    url: '/path/to/url',
                    success: function(data){
                        console.debug("**");
                    }, 
                    error: function(jqXHR, status, error){
                        console.debug("*** " + status + " : " + error + " : " + jqXHR.status);
                    },
                    cache: false
                });
            }

Now call the debounceClick function from the link to fix your issue.

Alternatively you could also use simple plain javascript without the throttle plugin to also achieve your result:

            var timeout;
            function test(){
                console.debug("*");
                $.ajax({
                    type: "GET",
                    dataType: "json",
                    url: '/path/to/url',
                    success: function(data){
                        console.debug("**");
                    }, 
                    error: function(jqXHR, status, error){
                        console.debug("*** " + status + " : " + error + " : " + jqXHR.status);
                    },
                    cache: false
                });
            }

            function click() {
                if(timeout) {
                         clearTimeout(timeout);
                }
                timeout = setTimeout(test, 1000);
            }

In this example, bind the click() function to your link.




回答9:


I faced the same issue, i was binding click event on the submit button and ajax runs twice. Instead of binding an event, i used onClick method on the button like below

<button onclick"myProcess()"></button>

and it solves my problem.



来源:https://stackoverflow.com/questions/15499647/jquery-ajax-get-request-executing-twice

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!