javascript - 为什么 phonegap click 事件会触发两次?

标签 javascript android cordova

我正在使用 phonegap 1.5.0 开发 android 应用

应用程序将数据存储在本地数据库中,并使用网络服务进行同步。 我正在使用一键单击来调用同步数据 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");
}

最佳答案

我找到的唯一解决方案是使用点击而不是点击,它会解决问题。

关于javascript - 为什么 phonegap click 事件会触发两次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15921143/

相关文章:

javascript - Android Javascript HTML 将包名称显示为值

android - 如何扩展android中的基本 Activity ?

android - 谷歌地图不显示

javascript - 在 PhoneGap 中链接 SQLite 调用

javascript - 将 cordova-plugin-firebase-authentication auth 转换为 Firebase JS-SDK auth

javascript - React - 单击不是其子组件的组件时呈现组件

javascript - Ace Editor 添加 Marker 抛出错误

javascript - 如何在 AngularJS 中隐藏 URL 中的选择性数据

android - 包含图像按钮的 Activity 加载时间过长

iphone - Testflight错误: This build doesn't support iPhone 5c GSM.请求开发者支持您的设备