簡體   English   中英

在使用 jQuery 調用 ajax function 之后更新全局變量

[英]Updating global variable after ajax function call with jQuery

不知道為什么以下不起作用。 我希望有人能解釋一下。

我有一個全局參數,用於重新表示數據庫中某個項目的某個 id。 現在為了檢查數據庫是否應該更新或是否應該為該項目創建一個新條目,如果設置了變量,我在進行 ajax 調用之前檢查。 如果設置了變量,我知道我必須更新數據庫,如果沒有設置,我知道我必須插入數據庫。 然后在服務器端我返回一個新生成的 id 以防插入,否則只返回舊 id 以防更新。 我使用 jQuery 表單並順便驗證插件(因此 function 調用 ajaxSubmit())。 但是,submitHandler 的成功 function 中的賦值似乎不起作用(我已經檢查過 data.poiId 返回了可疑的結果)。

$(document).ready(function() {

    // Function which examines window.location.href and extracts a numerical id if there is one specified in the query
    var id = getParameter('poiId')

   ...

   },
   submitHandler : function(form) {
       var str = 'submitPOI.php';
       if (id.length > 0) str += '?poiId=' + id;

       $(form).ajaxSubmit({
           url : str,
           type : 'POST',
           dataType : 'json',
           success : function(data) {
               id = data.poiId     // Update POI id with response from server
           } 
       });
   }

   ...
});

在我看來,您的 id 變量不是全局變量,因為它在 $(document).ready() function 中聲明。 將其移出 function 並檢查它是否有效。

暫無
暫無

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

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