簡體   English   中英

jQuery.when,無法獲取gata

[英]jQuery.when, cannot get gata

我想知道為什么此代碼不起作用。

這是我的工作:

  • 使用電子郵件和密鑰,我可以找到腳本的路徑,該腳本有效;

  • 有了腳本,我做一個ajax請求並訪問一個函數-getScriptUrlPersonalizationValue ;

  • 這個函數給我一個值,在這種情況下是國家的值: 美國 ;

  • 我想知道為什么jQuery.when和.done函數不會返回國家/地區值。

我可以將其保存在全局范圍內,但是我想學習javaScript,我想輸入一個失敗的原因。

我試圖注釋代碼,但上面給出的解釋要好得多。

function getData(key) {

    var email = 'myemail@test.com',
        url = getScriptUrl(key, email); // returns the valid url towards the script

    return jQuery.ajax({
                url : url,
                dataType : 'script'
            }).then(function() {
                country = getScriptUrlPersVal('Country');

                console.log(country); // returns: 'United States'

                // And I pass it:

                return country;
            });
}

jQuery.when( getData() ).then(function (data, textStatus, jqXHR) {

    console.log(data); // returns: undefined - should return United States
    console.log(textStatus); // returns: success
    console.log(jqXHR);  // returns: Object { readyState=4, status=200, statusText="success", more...}

});

有任何想法嗎?

謝謝!

.then()處理程序是互斥的,並且不共享數據,正如其他人提到的那樣,這解釋了為什么getData.then()中的返回沒有意義。 最好只返回沒有附加.then()的jQuery.ajax,並在一個級別上全部處理。 然后,可以根據需要將多個“ then's”鏈接在一起。

function getData(key) {
    var email = 'myemail@test.com',
        url = getScriptUrl(key, email); // returns the valid url towards the script

    return jQuery.ajax({
                url : url,
                dataType : 'script'
           });
}

jQuery.when(getData()).then(function (data, textStatus, jqXHR) {
    country = getScriptUrlPersVal('Country');
    console.log(country); // returns: 'United States'
    console.log(data); // returns: undefined - should return United States
    console.log(textStatus); // returns: success
    console.log(jqXHR);  // returns: Object { readyState=4, status=200, statusText="success", more...}
});

這是使用Promise的經典問題-如果不小心,可能會出現多毛的分支。 保持鏈越簡單越好。

嘗試將屬性添加到AJAX響應數據,而不是返回值。

function getData(key) {

    var email = 'myemail@test.com',
        url = getScriptUrl(key, email); // returns the valid url towards the script

    return jQuery.ajax({
                url : url,
                dataType : 'script'
            }).then(function(data, textStatus, jqXHR) {
                country = getScriptUrlPersVal('Country');

                console.log(country); // returns: 'United States'

                // Try to set your country to data object of ajax response.
                data.country = country;
            });
}

jQuery.when( getData() ).then(function (data, textStatus, jqXHR) {
     console.log(data); // should return object with property .country
});

PS:我不確定該解決方案是否會起作用,但是您可以嘗試。

暫無
暫無

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

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