简体   繁体   中英

jQuery $.post fires twice?

I have this code, and for some reason my $.post function fires twice in quick succession (for 'journal/weather') according to Firebug. It still does this when I remove the "if (navigator.geolocation)", however, if I replace the $.post block with something like console.log('test'), it only fires once.

What's even weirder is when I place console.log('test') before the $.post function, then my event only fires once as well. I am assuming something is going on strange with jQuery. Anybody have any ideas?

if (navigator.geolocation)
    {
    navigator.geolocation.getCurrentPosition(function(position)
        {
        $.post('journal/weather', {latitude: position.coords.latitude, longitude: position.coords.longitude}, function(result)
            {
            if (typeof(result.current.temp) != 'undefined')
                {
                global.temperature = parseInt(result.current.temp, 10);
                global.temperature_slider.slider('value', global.temperature);
                }
            }, "json");
        });
    }

Okay, stranger still, sometimes it fires twice, sometimes once. 好的,仍然很陌生,有时它会发射两次,有时会发射一次。 How can the same piece of code give different results each time it is executed?

After some experimentation, I think this is a bug in Firefox. 经过一些试验,我认为这是Firefox中的错误。 Why? Because it happens not only with my page, but others. If I keep refreshing my page, roughly the first 10 times the navigator.geolocation.getCurrentPosition fires the callback function. However, at a point, it quits doing so. And once it reaches this point, it doesn't work for any other website that uses getCurrentPosition. And this problem never happens on Chrome or even IE. Searching Google, I found this:

http://groups.google.com/group/mozilla.feedback.firefox/browse_thread/thread/fecc3fb0bad6d0b8

It sounds like the code may be being called before the page is finished loading - hence console.log perhaps not yet being initialized.

Is your code code wrapped in a document.ready of some sort, eg

$(function () { if (navigator.geolocation) { ... } });

Just a guess. Would need to know more about the context in which the code appears to have a better stab at it.

Hope that helps and good luck.

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