Risposta breve, non è possibile, il primo A in AJAX sta per Asincrono, il che significa che la richiesta è ancora in corso quando si arriva alla dichiarazione di ritorno.
È può farlo con un (non asincrona) richiesta sincrona, ma è generalmente una Qualcosa Bad Thing
simile al seguente oughta restituire i dati.
function getPrice(productId, storeId) {
var returnHtml = '';
jQuery.ajax({
url: "/includes/unit.jsp?" + params,
async: false,
cache: false,
dataType: "html",
success: function(html){
returnHtml = html;
}
});
return returnHtml;
}
MA
A meno che non si ha realmente realmente bisogno di essere in grado di utilizzare il valore restituito da prova subito, sarete molto meglio il superamento di un callback in prova. Qualcosa di simile
function getPrice(productId, storeId, callback) {
jQuery.ajax({
url: "/includes/unit.jsp?" + params,
async: true,
cache: false,
dataType: "html",
success: function(html){
callback(html);
}
});
}
//the you call it like
getPrice(x,y, function(html) {
// do something with the html
}
Modifica Sheesh, voi siete più veloce di dire quello che ho detto :-)
fonte
2009-09-22 01:30:27
Gotchya - ho pensato che devo farlo. ma cosa succede se dovessi farlo? –
È difficile rispondere a questo senza sapere come intendevi usare il metodo getPrice(). A cosa serve? Come viene usato? È il codice a quel livello "esterno" che dovrà essere aggiustato. – cletus
Ok ho capito. Non mi ero reso conto che productId e storeId sarebbero stati inclusi nel campo di applicazione e posso effettivamente passare quella roba nella chiamata. –