-->

jquery pjax request sending twice

2019-02-08 17:28发布

问题:

I have a rails app and I keep getting a weird behavior with pjax requests. When I look into my development logs I could see that two requests are being made. The first request is pjax and the next one is not. As a result the page still reloads.

I appreciate if anyone could help me with this.

回答1:

The JQuery pjax plugin has a default error handler, that will simply reload the target page. This error handler gets called when the timeout has passed, which pjax sets very low. As a result, if your request takes too long, you will see two identical requests. The pjax request (probably with the _pjax attribute set), followed by another non-pjax request. In the browser you will likely see an entire page reload.

One thing I found in my situation, was that the response itself wasn't taking all that long. However, the HTML that was returned included a flash embed. I'm not sure if the pjax code gets its response before or after the flash embed is loaded.

To solve the problem, I changed my PJax code to look like...

$.pjax({
        url: xhr.getResponseHeader('Location'),
        container: '#container',
        timeout: 4000 // pick a suitable timeout
      });

Of course, this is calling pjax directly. If you are not calling it directly, you'll have to find a similar solution.



回答2:

I've also ran in to this issue - it looks like it is an issue related to browser caching. I've noticed that if I clear the history and cache it stops happening in Chrome. I haven't been able to resolve it yet but I imagine it has something to do with disabling browser caching?