2015-10-12 82 views
1

我試圖從Ajax調用中返回一個值,但無法找到正確的方法來執行此操作。這裏是我現在有:來自Ajax調用的返回值

function getCount() { 
    $.ajax({ 
     url: "php/get.php", 
     type: 'get', 
     dataType: 'html', 
     data: { location: "", category: "10" }, 
     async: false, 
     success: function(data) { 
      result = Math.ceil(data/20); 
     } 
    }); 
return result; 
} 

正如你所看到的,我用async false現在折舊。有沒有另一種方式喲返回這個功能,像我現在沒有使用async: false

+2

[如何從異步調用返回響應?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) –

回答

1

此時您不能return result,因爲這是異步調用。相反,您可以退還承諾並解決問題。遵守以下...

function getCount() { 
    return $.ajax({ 
     url: 'php/get.php', 
     type: 'get', 
     dataType: 'html', 
     data: { location: '', category: '10' }, 
    }); 
} 

與樣品的使用...

var result; 

getCount().then(function(response) { // -- asynchronous 
    result = Math.ceil(response/20); 
}); 

此外,一些語法速記可能有興趣在這裏 - jQuery.get()

function getCount() { 
    return $.get('php/get.php', { location: '', category: '10' }); 
} 

JSFiddle Link - 演示


或者,如果你想與getCount()執行您Math邏輯,而不是你的then()回調,你可以用下面的方式做到這一點...

function getCount() { 
    var deferred = $.Deferred(); 

    $.get('php/get.php', { location: '', category: '10' }, function(response) { 
     deferred.resolve(Math.ceil(response/20)); 
    }); 

    return deferred.promise(); 
} 

getCount().then(function(response) { 
    console.log(response) // Math.ceil value 
}); 

JSFiddle Link - 二次演示

查看Deferred Object docs全面瞭解這裏發生了什麼

+0

很好的信息。如果我想存儲使用的getCount()Math.ceil值,我將如何存儲它?我只是讓變量等於'getCount()。then(function(response){});'? – user081608

+0

不幸的是,你不能這樣做。典型的方法是聲明一個空變量,然後在解析promise後使用它,或者在'then()'回調函數或者某個地方的事件處理函數中(解決之後的任何地方)。如果你想在回調之下嘗試使用它,你會得到'undefined'。我[在JSFiddle中演示它](http://jsfiddle.net/51f2zw5t/)供你學習,並且包含了一些有希望幫助的評論! – scniro

+0

好吧非常有趣。所以如果我想要得到那個值,我需要把代碼放在'then()'中並且像這樣工作,而不是試圖檢索它? – user081608