为什么PhoneGap的点击事件会触发两次?

4
我正在使用PhoneGap 1.5.0开发Android应用程序。该应用程序将数据存储在本地数据库中,并使用Web服务进行同步。我使用一个按钮单击调用同步数据JavaScript函数。我发现的问题是:这个同步按钮的点击事件会触发两次。单个记录会被上传两次,并且在服务器数据库中的上传时间相同。如何避免这种情况?谢谢。
编辑: 大家好,抱歉回复有些晚了;我忙于一些优先工作。在按钮上单击时调用SyncData()函数。以下是代码:
document.addEventListener("DOMContentLoaded", onDeviceReady, false);
var db;
var maxrecords = 0;
var recordsprocessed = 0;
var urlstart = "http://www.mywebsite.com/";

function onDeviceReady() {
    db = window.openDatabase("LocalDB", "1.0", "PhoneGap Demo", 50 * 1024 * 1024);
}

function SyncData() {
    maxrecords = 0;
    recordsprocessed = 0;
    db.transaction(queryDB, errorCB, successCB);
}

function queryDB(tx) {
    var entriestoupload = 0;
    var profimagetoupload = 0;

    //check how many entries are to be synchronized
    tx.executeSql('SELECT count(*) as cnt FROM tblEntries WHERE IsUploaded=0', [], function(tx, results) {
        entriestoupload = parseInt(results.rows.item(0)['cnt']);
        //check how many profile images are to be uploaded
        tx.executeSql('SELECT count(*) as cnt FROM tblEntries WHERE IsProfileImageUploaded=0', [], function(tx, results) {
            profimagetoupload = parseInt(results.rows.item(0)['cnt']);

            //synch proceeds if there is any record which is not sychronised
            if (entriestoupload > 0 || profimagetoupload > 0) {
                var dataMsg = '';
                var porofimgMsg = '';
                if (entriestoupload > 0) dataMsg = entriestoupload + ' entry, ';
                if (profimagetoupload > 0) porofimgMsg = profimagetoupload + ' profile image ';

                // give user exact info about what will be synchronized 
                if (confirm(dataMsg + porofimgMsg + ' are not synchronized.\n Do you want to start synchronisation? \n Please wait till synch successfull message appears.')) {

                    //start synchronisation
                    tx.executeSql('SELECT * FROM tblEntries ORDER BY DateOfRegistration DESC', [], uploadData, errorCB);
                }
            } else {
                alert('All records are already Synchronized.');
            }
        }, errorCB);
    }, errorCB);
}

function uploadData(tx, results) {
    var len = results.rows.length;
    maxrecords = len;
    var Synched = 0;
    if (len > 0) {
        for (var i = 0; i < len; i++) {
            var row = results.rows.item(i);
            var LocalId = row['LocalId'];
            var DateOfRegistration = getDateTimeformatMySql(String(row['DateOfRegistration']));
            var DateOption = getDateTimeformatMySql(String(row['DateOption']));
            var VolunteerId = row['VolunteerId'];
            var IsUploaded = row['IsUploaded'];
            var LiveId = row['LiveId'];
            var ProfileImagePath = row['ProfileImagePath'];
            var IsProfileImageUploaded = parseInt(row['IsProfileImageUploaded']);
            var params = null;
            var weburl = null;

            if (IsUploaded == 0) {

                //set parameters for web service
                params = "LocalId=" + LocalId + "&OrganizationName=" + row['OrganizationName'] + "&FirstName=" + row['FirstName'] + "&LastName=" + row['LastName'] + "&EmailAddress=" + row['EmailAddress'] + "&MobileNumber=" + row['MobileNumber'] + "&Country=" + row['Country'] + "&State=" + row['State'] + "&City=" + row['City'] + "&Lattitude=" + row['Lattitude'] + "&Longitude=" + row['Longitude'] + "&Website=" + row['Website'] + "&DateOption=" + DateOption + "&TimeOption=" + row['TimeOption'] + "&NumberOption=" + row['NumberOption'] + +"&RadioOption=" + row['RadioOption'] + "&Details=" + row['Details'] + "&CheckBoxoption=" + row['CheckBoxoption'] + "&DropDownOption=" + row['DropDownOption'] + "&DateOfRegistration=" + DateOfRegistration + "&VolunteerId=" + VolunteerId;

                //web service url
                weburl = urlstart + "mywebserviceurl";

                try {
                    $.ajax({
                        async: false,
                        type: "POST",
                        url: weburl,
                        data: params,
                        dataType: "json",
                        success: function(data, textStatus, jqXHR) {
                            if (data.Success == "0") {
                                alert('web services error:\n' + data.Message);
                            }
                            if (data.Success == "1") {
                                try {
                                    LiveId = parseInt(String(data.LiveId));
                                    IsUploaded = 1;

                                    //Update local database to set IsUploaded and LiveId
                                    tx.executeSql("UPDATE tblEntries SET LiveId= " + LiveId + " ,IsUploaded=1 WHERE LocalId= " + LocalId, [], function(tx, results) {
                                        Synched = Synched + 1; /*alert(LiveId);*/
                                    }, errorCB);
                                    //check if profile image exists or not
                                    if (ProfileImagePath != undefined) {
                                        uploadImage(LiveId, LocalId, ProfileImagePath, '1', '');
                                    }

                                } catch (e) {
                                }
                            }
                        },
                        error: function() {
                            alert("There was an error loading the feed");
                        }
                    });
                } catch (e) {
                }
            } else {
                //check if data is uploaded and image is not uploaded
                if (IsProfileImageUploaded == 0 && ProfileImagePath != undefined) {
                    uploadImage(LiveId, ShopId, ProfileImagePath, '1', '');
                }
            }
        }
    }
} // end of querySucess function

//function to upload image

function uploadImage(LiveId, LocalId, ImagePath, UploadType, CreationDate) {
    try {

        var options = new FileUploadOptions();
        options.fileKey = "file";
        options.fileName = ImagePath;
        options.mimeType = "image/jpg";

        var params = new Object();
        params.LiveId = LiveId;
        params.LocalId = LocalId;
        params.UploadType = UploadType;
        params.CreationDate = CreationDate;
        options.params = params;
        options.chunkedMode = false;
        var ft = new FileTransfer();
        var url = urlstart + "mywebservice_url_to_uploadimage";

        ft.upload(ImagePath, url, win, fail, options, false);

    } catch (e) {
        console.error("Survey App Err :" + e.message);
    }
}

function win(r) {
    var jsonresponse = r.response.substring(r.response.indexOf('{'), r.response.indexOf('}') + 1);
    var obj = $.parseJSON(jsonresponse);

    if (obj.Success == "1") {

        var LocalId = parseInt(obj.LocalId);
        var UploadType = parseInt(obj.UploadType);
        if (UploadType == 1) {
            db.transaction(function(tx) {
                tx.executeSql("UPDATE tblEntries SET IsProfileImageUploaded=1 WHERE LocalId=?", [LocalId], function(tx, results) {
                }, errorCB);
            }, errorCB, successCB);
        }
    }
}

function fail(error) {
    alert("There was an error uploading image");
}

2
你能贴一些代码吗? - karthick
我曾经在PhoneGap应用程序中遇到类似的问题,搜索指责jQuery Mobile或周围的某些东西,但无法找到真正的罪魁祸首。幸运的是,我成功地摆脱了这个PhoneGap垃圾并重写了原生应用程序。 - Marcin Orlowski
2
我也遇到过这个问题...问题出在错误使用了jquery。你不能在多个HTML页面上加载jquery。如果这样做,事件会触发两次。 - Ferdi Duisters
@Napster:请问您能否添加您的代码,用于调用同步数据JavaScript函数的按钮单击事件? - Narendra Singh
@karthick和Narendra DroidWorm,请检查我的代码编辑。 - Amol Chakane
1个回答

0

我发现唯一的解决方案是使用tap而不是click,这样就能解决问题。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接