在PhoneGap的HTTP请求 [英] HTTP Requests in Phonegap

查看:193
本文介绍了在PhoneGap的HTTP请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个奇怪的问题与PhoneGap的。我XMLHtt prequests火的两倍;我使用的一个应用程序XMLHtt prequests我发展到创建活动选择的动态列表。 jQuery的也是我使用的库之一。

I have a weird problem with Phonegap. My XMLHttpRequests fire twice; I'm using XMLHttpRequests in an app I'm developing to create a dynamic list of events to select. jQuery is also one of the libs I'm using.

任何时候,我用一个XMLHtt prequest,无论是香草或jQuery的,但它确实两次,即使它应该只运行一次。有没有其他人遇到了这个问题?

Any time I use an XMLHttpRequest, either vanilla or jQuery, it does it twice, even though it should only run once. Has anyone else ran into this problem?

一些例如code在这里:

Some example code here:

(function(){
    var request = new XMLHttpRequest();
    request.open("GET", "http://{site-url-hidden-for-privacy}/events/list", true);
    request.onreadystatechange = function(){
    if(request.readyState == 4){
        if(request.status == 200 || request.status == 0){
            parse_events(JSON.parse( request.responseText ));
        }               
    }
}
request.send();
})();

在XMLHtt presponse文本是一个JSON数组,并parse_events只是采用了阵列,并使用它来创建一组选择选项菜单。

the XMLHttpResponse text is a JSON array, and parse_events simply takes that array and uses it to create a set of select options for a menu.

有谁知道为什么会火的两倍,基本上是建立两个选项,每个事件的时候应该只有一个?

Does anyone know why this would fire twice, essentially creating two options for each event, when there should only be one?

推荐答案

好吧,我想通弄明白了。我在做这个项目的同事,我们忘了侦听deviceready事件,火灾,因为我们使用PhoneGap的。我们具有约束力的在线和离线的事件时,窗口中加载,而不是当设备准备好了。

Okay, I got it figured out. I was working on this project with a co-worker, and we forgot to listen for the deviceready event to fire, since we're using phonegap. We were binding the "online" and "offline" events when the window loaded, not when the device was ready.

document.addEventListener("DOMContentLoaded", function(){
    document.addEventListener("online", function(){...}, false);
    document.addEventListener("offline", function(){...}, false);
}, false);

解决方法:

document.addEventListener("DOMContentLoaded", function(){
    document.addEventListener("deviceready",function(){
        document.addEventListener("online", function(){...}, false);
        document.addEventListener("offline", function(){...}, false);
    },false);
}, false);

我不知道为什么,因为它没有任何意义总量,但我认为不会通过deviceready是导致HTTP请求去了两次,第一次加载的时候,有一次当设备准备

I'm not sure why, as it doesn't make total sense, but I think not going through "deviceready" was causing the HTTP request to go twice, once when the page loaded, and once when the device was ready.

此修复程序是使它只能去当设备准备好了,如上图所示。

The fix was to make it only go when the device was ready, as shown above.

这篇关于在PhoneGap的HTTP请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆