Pregunta

Quiero regresar StudentId para usar en otro lugar fuera del alcance del $.getJSON()

j.getJSON(url, data, function(result)
{
    var studentId = result.Something;
});

//use studentId here

Me imagino que esto tiene que ver con el alcance, pero no parece funcionar de la misma manera. C# hace

¿Fue útil?

Solución

Sí, mi respuesta anterior no funciona porque no presté atención a tu código.:)

El problema es que la función anónima es una función de devolución de llamada, es decir.getJSON es una operación asíncrona que regresará en algún momento indeterminado, por lo que incluso si el alcance de la variable estuviera fuera de esa función anónima (es decir,un cierre), no tendría el valor que usted cree que debería:

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

Cualquier código que desee ejecutar con el valor de StudentId establecido por la llamada getJSON debe ejecutarse dentro esa función de devolución de llamada o después la devolución de llamada se ejecuta.

Otros consejos

no parece funcionar de la misma manera que C#

Para lograr un alcance similar al de C#, deshabilite las operaciones asíncronas y establezca el tipo de datos en json:

var mydata = [];
$.ajax({
  url: 'data.php',
  async: false,
  dataType: 'json',
  success: function (json) {
    mydata = json.whatever;
  }
});

alert(mydata); // has value of json.whatever

Incluso más sencillo que todo lo anterior.Como se explicó anteriormente $.getJSON ejecuta async lo que causa el problema.En lugar de refactorizar todo su código al $.ajax método simplemente inserte lo siguiente en la parte superior de su archivo .js principal para deshabilitar el comportamiento asíncrono:

 $.ajaxSetup({
   async: false
 });

¡buena suerte!

Si desea delegar en otras funciones, también puede extender jquery con $.fn.notación así:


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, si has serializado un objeto con el StudentId propiedad entonces creo que será:

var studentId;
function(json) {
    if (json.length > 0)
        studentId = json[0].StudentId;
}

Pero si sólo estás devolviendo el StudentId en sí mismo tal vez sea:

var studentId;
function(json) {
    if (json.length > 0)
        studentId = json[0];
}

Editar:O tal vez .length ni siquiera es necesario (solo he devuelto colecciones genéricas en JSON).

Edición #2, esto funciona, acabo de probar:

var studentId;
jQuery.getJSON(url, data, function(json) {
    if (json)
        studentId = json;
});

Edición #3, aquí está el JS real que usé:

$.ajax({
    type: "POST",
    url: pageName + "/GetStudentTest",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    data: "{id: '" + someId + "'}",
    success: function(json) {
        alert(json);
    }
});

Y en 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
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top