jQuery $ .post会发射两次?

时间:2010-07-16 18:15:11

标签: javascript jquery post geolocation

我有这个代码,根据Firebug,由于某种原因,我的$ .post函数连续两次触发(对于'journal / weather')。当我删除“if(navigator.geolocation)”时,它仍然会这样做,但是,如果我用console.log('test')替换$ .post块,它只会触发一次。

当我在$ .post函数之前放置console.log('test')时,甚至更奇怪的是,我的事件也只触发一次。我假设jQuery正在发生一些奇怪的事情。有人有什么想法吗?

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");
        });
    }

编辑:好吧,陌生人仍然,有时会发射两次,有时一次。每次执行时,同一段代码如何给出不同的结果?

编辑2:经过一些实验,我认为这是Firefox中的一个错误。为什么?因为它不仅发生在我的页面上,还发生在其他页面上。如果我一直刷新我的页面,大约前10次navigator.geolocation.getCurrentPosition会触发回调函数。但是,在某一点上,它会退出。一旦达到这一点,它就不适用于使用getCurrentPosition的任何其他网站。这个问题在Chrome甚至IE上都不会发生。搜索Google,我发现了这个:

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

1 个答案:

答案 0 :(得分:0)

听起来好像在页面加载完成之前可能会调用代码 - 因此console.log可能尚未初始化。

您的代码是否包含在某种document.ready中,例如

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

只是一个猜测。需要更多地了解代码似乎更好地抨击它的上下文。

希望有所帮助,祝你好运。