Access json data outside of $.getJSON()

后端 未结 3 1932
南笙
南笙 2021-01-02 22:48
$(document).ready(function () {
    var value = getParmsVals()[\"search\"];
    $.getJSON(\'/api/search/GetQuestionByKey/\' + value, function (jsonData) {
        $(         


        
相关标签:
3条回答
  • 2021-01-02 22:53

    You can also put your variable on the object and use .bind(), like so:

    this.fullname = "default";
    
    $.getJSON('/api/search/GetUserById/' + userId, function (jsonData) {
       this.fullname = jsonData.firstname + " " + jsonData.lastname;
    }.bind(this));
    
    0 讨论(0)
  • 2021-01-02 23:01

    You wouldn't return from an async method, as you can see, it doesn't work! What you need is a callback function, consider:

    function getAuthorName(userId, callback) {
        var fullname = "default";
        $.getJSON('/api/search/GetUserById/' + userId, function (jsonData) {
            fullname = jsonData.firstname + " " + jsonData.lastname;
            callback(fullname);
        });
    }
    

    Notice how we pass in callback and then call it at the end of your get call? Now call this method like so:

    getAuthorName(userID, function(name) {
        console.log(name);
    });
    

    And now you have access to fullname in that callback function!

    0 讨论(0)
  • 2021-01-02 23:10

    I like the answer by @tymeJV it is an easy solve to the problem

    I just wanted to point out that solving the big picture of having easily accessible data inside Javascript is a great reason why data-centric JS frameworks exist

    http://knockoutjs.com/ http://backbonejs.org/ http://angularjs.org/

    0 讨论(0)
提交回复
热议问题