簡體   English   中英

jQuery Ajax競賽條件最佳實踐

[英]jQuery Ajax Race Condition best practice

在一個button.click(function(){}); 我有以下代碼:

var userId = $("#user-permission-edit").val();
        var peId = $("#user-permission-entity-list").val();
        var newParentPEId = $("#new-parent-pe").val();
        var newPeName = $("#pe-name-add").val();

        $.ajax({
            type: "POST",
            url: 'AddNewPE',
            data: { 'targetUserId': userId, 'targetPEId': peId, 'newPeParentId': newParentPEId, 'newPeName': newPeName},
            success: function (data) {
                var dataObj = jQuery.parseJSON(data);
                console.log(dataObj);

                if (dataObj.status == "success") {
                    alert("Permissions have been updated.");
                }
                //update user PEs combo

            }
        });

但是,我擔心變量的可能競爭條件沒有及時獲取有關ajax調用的值。

這樣的東西會更安全嗎?

  var userId = $("#user-permission-edit").val();
    var peId = $("#user-permission-entity-list").val();
    var newParentPEId = $("#new-parent-pe").val();
    var newPeName = $("#pe-name-add").val();


    $.when(function() {
         userId = $("#user-permission-edit").val();
         peId = $("#user-permission-entity-list").val();
         newParentPEId = $("#new-parent-pe").val();
         newPeName = $("#pe-name-add").val();

    }).done(function() {
        $.ajax({
            type: "POST",
            url: 'AddNewPE',
            data: { 'targetUserId': userId, 'targetPEId': peId, 'newPeParentId': newParentPEId, 'newPeName': newPeName},
            success: function (data) {
                var dataObj = jQuery.parseJSON(data);
                console.log(dataObj);

                if (dataObj.status == "success") {
                    alert("Permissions have been updated.");
                }
                //update user PEs combo

            }
        });

    });

這有必要嗎?

$('....').val()方法是一個同步調用-在您收到該元素的值之前,您的腳本執行不會超過該行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM