如何从$ .getJSON函数返回变量

时间:2020-03-05 18:44:05  来源:igfitidea点击:

我想返回StudentId以在$ .getJSON()范围之外的其他地方使用

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

//use studentId here

我想这与范围界定有关,但似乎与cdoes的工作方式不同

解决方案

回答

是的,我之前的答案不起作用,因为我没有对代码给予任何关注。 :)

问题在于匿名函数是一个回调函数,即getJSON是一个异步操作,它将在某个不确定的时间点返回,因此,即使变量的范围不在该匿名函数(即闭包)之外,也不会具有我们认为应该的价值:

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

要使用由getJSON调用设置的studentId值执行的任何代码都需要在该回调函数内或者在回调执行后发生。

回答

嗯,如果我们已经使用" StudentId"属性序列化了一个对象,那么我认为它将是:

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

但是,如果我们只是返回StudentId本身,则可能是:

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

编辑:也许甚至不需要.length(我只以JSON返回了通用集合)。

编辑#2,这有效,我刚刚测试过:

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

编辑#3,这是我使用的实际JS:

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

并在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

回答

如果我们希望委托给其他功能,还可以使用$ .fn扩展jquery。像这样的符号:

var this.studentId = null;

$.getJSON(url, data, 
    function(result){
      $.fn.delegateJSONResult(result.Something);
    }
);

$.fn.delegateJSONResult = function(something){
  this.studentId = something;
}

回答

it doesn't seem to work the same way
  c# does

要完成类似于C#的作用域,请禁用异步操作并将dataType设置为json:

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

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