簡體   English   中英

在jQuery中調用函數ajax成功響應只能工作一次但不能兩次

[英]Calling function inside jQuery ajax success response works once but not twice

我有一個頁面,我輸入卡片的名稱,卡片的詳細信息通過AJAX呈現。 我在這個例子中刪除了很多與該問題無關的代碼,並且我已經測試了這個簡化的代碼並且它再現了相同的錯誤。

神秘的是它在第一次運行testSelectedCardDetails函數時工作正常。 它調用setNameCardIsFromField並完成它的意圖。 第二次通過它死於控制台顯示:

Uncaught TypeError: setNameCardIsFromField is not a function

那是怎么回事? 老實說,我不知道jQuery如何能夠解決這個問題,所以我轉向stackoverflow世界,乞求從這種瘋狂中獲得救贖。 ;)

    function testSelectedCardDetails(cardName) {

        var cardTestInfoArray = [];

        $.ajax({
            url: 'includes/getCardAndSetDataViaAJAX.php',           
            type: 'POST',
            cache: false,
            async: false, // if set to true then the data doesn't get here fast enough to run commands in 'success'
            dataType: 'json',
            data: { callThis: "testSelectedCardDetails", thisCardName: cardName},
            error: function(data){
                console.log("AJAX failed to get card info.");
            },
            success: function(data) {                   

                $.map(data, function (value) { cardTestInfoArray = value; });
                cardPresentInfo['printings'] = cardTestInfoArray['printings'];

                //automatically set setNameCardIsFrom field
                setNameCardIsFromField(cardPresentInfo['printings']);
            }
        });
    }

這是被調用的函數:

    function setNameCardIsFromField(setCode) {

        $.ajax({
            url: 'includes/getCardAndSetDataViaAJAX.php',           
            type: 'POST',
            cache: false,
            async: false,   // if set to true then the data doesn't get here fast enough to run commands in 'success'
            dataType: 'text',
            data: { callThis: "setNameCardIsFromField", thisSetCode: setCode},
            error: function(data){
                console.log("AJAX failed to get card info.");
            },
            success: function(setName) {
                //console.log(setName);
                setNameCardIsFromField = document.querySelector('#setNameCardIsFrom');
                setNameCardIsFromField.value = setName; 
            }
        });
    }

你覆蓋了這個功能:

 setNameCardIsFromField = document.querySelector('#setNameCardIsFrom');

假設它是全局的(通常很糟糕)。

不相關,但是使用async: false ,更好地做正確而不是破解它,例如回調,承諾,等等。

暫無
暫無

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

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