Come posso restituire una variabile da una funzione $.getJSON
-
09-06-2019 - |
Domanda
voglio ritornare StudentId
da utilizzare altrove al di fuori del scopo del $.getJSON()
j.getJSON(url, data, function(result)
{
var studentId = result.Something;
});
//use studentId here
Immagino che questo abbia a che fare con l'ambito, ma non sembra funzionare allo stesso modo C# fa
Soluzione
Sì, la mia risposta precedente non funziona perché non ho prestato attenzione al tuo codice.:)
Il problema è che la funzione anonima è una funzione di callback, ad es.getJSON è un'operazione asincrona che verrà restituita in un momento indeterminato, quindi anche se l'ambito della variabile fosse esterno a quella funzione anonima (ad es.una chiusura), non avrebbe il valore che penseresti che dovrebbe:
var studentId = null;
j.getJSON(url, data, function(result)
{
studentId = result.Something;
});
// studentId is still null right here, because this line
// executes before the line that sets its value to result.Something
È necessario che venga eseguito anche qualsiasi codice che desideri eseguire con il valore di studentId impostato dalla chiamata getJSON entro quella funzione di callback o Dopo viene eseguita la richiamata.
Altri suggerimenti
Non sembra funzionare allo stesso modo in cui C# fa
Per ottenere un ambito simile a C#, disabilita le operazioni asincrone e imposta dataType su json:
var mydata = [];
$.ajax({
url: 'data.php',
async: false,
dataType: 'json',
success: function (json) {
mydata = json.whatever;
}
});
alert(mydata); // has value of json.whatever
Ancora più semplice di tutto quanto sopra.Come spiegato in precedenza $.getJSON
esegue asincrono che causa il problema.Invece di rifattorizzare tutto il tuo codice nel file $.ajax
metodo basta inserire quanto segue nella parte superiore del file .js principale per disabilitare il comportamento asincrono:
$.ajaxSetup({
async: false
});
buona fortuna!
Se desideri delegare ad altre funzioni puoi anche estendere jquery con $.fn.notazione in questo modo:
var this.studentId = null;
$.getJSON(url, data,
function(result){
$.fn.delegateJSONResult(result.Something);
}
);
$.fn.delegateJSONResult = function(something){
this.studentId = something;
}
var context;
$.ajax({
url: 'file.json',
async: false,
dataType: 'json',
success: function (json) {
assignVariable(json);
}
});
function assignVariable(data) {
context = data;
}
alert(context);
hmm, se hai serializzato un oggetto con il file StudentId
proprietà allora penso che sarà:
var studentId;
function(json) {
if (json.length > 0)
studentId = json[0].StudentId;
}
Ma se stai semplicemente restituendo il file StudentId
stesso forse è:
var studentId;
function(json) {
if (json.length > 0)
studentId = json[0];
}
Modificare:O forse .length
non è nemmeno richiesto (ho restituito solo raccolte generiche in JSON).
Modifica n. 2, funziona, ho appena provato:
var studentId;
jQuery.getJSON(url, data, function(json) {
if (json)
studentId = json;
});
Modifica n. 3, ecco il JS effettivo che ho usato:
$.ajax({
type: "POST",
url: pageName + "/GetStudentTest",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "{id: '" + someId + "'}",
success: function(json) {
alert(json);
}
});
E in aspx.vb:
<System.Web.Services.WebMethod()> _
<System.Web.Script.Services.ScriptMethod()> _
Public Shared Function GetStudentTest(ByVal id As String) As Integer
Return 42
End Function