简体   繁体   English

$ .getJSON回调帮助-不是函数

[英]$.getJSON Callback Help - Not a Function

My context is as follows: 我的情况如下:

I have a variable 'qq' - I want to assign data to this variable from an API call, and once the data has been assigned, I then use this data in a paint/binding process. 我有一个变量'qq'-我想通过API调用将数据分配给该变量,一旦分配了数据,就可以在绘画/装订过程中使用此数据。

The API call and assigning to var 'qq' works fine - but I cant seem to get my callback to work - I keep getting an error: callback() is not a function API调用并分配给var'qq'可以正常工作-但我似乎无法使我的回调正常工作-我不断收到错误消息:callback()不是函数

This is what my code currently looks like: 这是我的代码当前的样子:

 var qq = []; // binding function - to be run after data loader has completed function sayIamDone() { alert('I Am Done'); // do data bindings with qq } // load data from api into var qq function dataLoader(inp,callback) { let url = 'http://localhost:65232/api/layercolor/' + inp; console.log(url); $.getJSON(url,function(result) { qq = eval('({' + result + '})'); //console.log(qq); callback(); }); } // call data loader dataLoader('Prov', sayIamDone()); 

From the above I get the following error in my chrome console: 从以上内容,我在Chrome控制台中收到以下错误:

Uncaught TypeError: callback is not a function 未捕获的TypeError:回调不是函数

I have tried the following - which seems to work: 我尝试了以下方法-似乎可行:

 dataLoader('Prov', function () { alert('I Am Done');}); 

but it is not ideal in my context, as I want to call dataLoader('Prov',XXX()) where XXX() could be a number of different functions using the newly loaded values in qq 但这在我的上下文中并不理想,因为我想调用dataLoader('Prov',XXX()),其中XXX()可能是使用qq中新加载的值的许多不同函数

Any suggestions as to where I am missing the boat please? 关于我想念船的地方有什么建议吗?

change: 更改:

dataLoader('Prov', sayIamDone());

to

dataLoader('Prov', sayIamDone);

because: 因为:

sayIamDone is function , sayIamDone() is the result of function.Normally, sayIamDone() is undefined or return value in the sayIamDone ; sayIamDone是函数, sayIamDone()是函数的结果。 sayIamDone()sayIamDone()undefined或者在sayIamDone返回值;

want to use arguments?you can do this: 要使用参数吗?可以执行以下操作:

dataLoader('Prov', callFunc(n));

function callFunc(arg) {
    return function() {
        sayIamDone(arg);
    };
}

or more arguments?you can do this by spread 或更多论点?您可以通过传播做到这一点

dataLoader('Prov', callFunc(n));

function callFunc(...arg) {
    return function() {
        sayIamDone.apply(null, arg);
    };
}

By running dataLoader('Prov', sayIamDone()); 通过运行dataLoader('Prov', sayIamDone()); you are passing to dataLoader the result of sayIamDone function. 您正在将sayIamDone函数的结果传递给dataLoader You have to pass it without parenthesis in order to pass the function itself. 您必须不带括号地传递它,以传递函数本身。

dataLoader('Prov', sayIamDone);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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