How can I return a variable from a $.getJSON function

前端 未结 6 1337
迷失自我
迷失自我 2020-11-27 03:01

I want to return StudentId to use elsewhere outside of the scope of the $.getJSON()

j.getJSON(url, data, function(result)
         


        
6条回答
  •  Happy的楠姐
    2020-11-27 03:37

    hmm, if you've serialized an object with the StudentId property then I think that it will be:

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

    But if you're just returning the StudentId itself maybe it's:

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

    Edit: Or maybe .length isn't even required (I've only returned generic collections in JSON).

    Edit #2, this works, I just tested:

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

    Edit #3, here's the actual JS I used:

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

    And in the aspx.vb:

     _
     _
    Public Shared Function GetStudentTest(ByVal id As String) As Integer
        Return 42
    End Function
    

提交回复
热议问题