按名称/键回调json值

时间:2015-11-19 13:08:44

标签: javascript jquery json ajax callback

使用此功能,我试图通过名称/密钥从json url获取许可证名称 我的json看起来像这样:

[{"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
});

我需要的是使用类似的内容获取truefalse

getLicenceName(Gallery);

我需要在我的函数中使用它,例如:if(getLicenceName(Gallery)=false)...

2 个答案:

答案 0 :(得分:1)

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
});

会做的伎俩。

答案 1 :(得分:1)

你不能真正做if(getLicenceName(Gallery) == false),因为AJAX请求是异步的,但你可以这样做:

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) {
      ...
    }
});