简体   繁体   中英

callback json value by name/key

With this function I'm trying to get the licence name from a json url by name/key my json looks like this:

[{"Gallery":true,"Responsive":true,"Main":true,"Seasonal":true}]

js:

function getLicenseName(name, callback){
    var license = 'default'
    $.getJSON(adl+'DesignTemplateBuilder.aspx?GetLicense=1', function(data){
        /*
        licence = data[0].Gallery;
        respValue = data[0].Responsive;
        seasonalValue = data[0].Seasonal;
        */
        licence = data[0].name;
        callback(licence)
    }); 
}
getLicenseName(name, function(Responsive) {
    console.log(name);
    //this returns empty right now
});

What I need is to get the true or false value using something like this

getLicenceName(Gallery);

I need to use it in my functions eg: if(getLicenceName(Gallery)=false)...

function getLicenseName(callback){
    $.getJSON(adl+'DesignTemplateBuilder.aspx?GetLicense=1', function(data){
        callback(data)
    }); 
}
getLicenseName(function(data) {
    console.log(data[0].Gallery);
    //this returns empty right now
});

Will do the trick.

You can't really do if(getLicenceName(Gallery) == false) because the AJAX request is asynchronous, but you can do it this way:

function getLicenseName(name, callback) {
    $.getJSON(adl+'DesignTemplateBuilder.aspx?GetLicense=1', function(data){

       // pass back the name parameter
       callback(data[0][name])
    }); 
}

// use quotes around the name
getLicenseName('Gallery', function (name) {
    if (name) {
      ...
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM