如果这是一个重复的问题,我深表歉意。我已经完成了研究,但仍然无法得出答案:
我正在编写一个小型 JSONP API。期望的结果:
程序员创建 JSON 类的实例。
var json = new jsonpRequest ( "http://url.to.web_service", searchParam //passed in as an associative array );
然后程序员声明
var myJSON = jsonpRequest.getJsonP()
这会将 JSONP 返回到 myJSON 变量中进行处理。
当构造类的实例时,API 成功接收参数,生成带有所需参数的服务链接,并使用此函数通过脚本标记将其注入(inject) DOM:
jsonpRequest.prototype.fetchJsonp = function(){
var request = that.getRequest();
//creates a script element
var jsonpCall = document.createElement('script');
//gets jsonp request
jsonpCall.src = request;
//adds script to DOM, which goes on to request the JSONP from the service.
document.head.appendChild(jsonpCall);
};
编辑:为了清楚起见:这肯定会返回所请求的数据集。
我用作回调的函数是:
jsonpRequest.prototype.processCallback = function(data){
alert(data);
that.setListOfResults(data);
};
它在链接中被称为:&callback=jsonpRequest.prototype.processCallback
processCallback
函数从请求中获取数据,并使用 setListOfResults
函数将其存储在类中的变量中。
存储数据后,我想将请求中的数据返回到 myJSON
变量。这是程序员在流程的第 2 步中调用的 getJsonp
函数:
jsonpRequest.prototype.getJsonp = function(){
that.buildRequest();
that.fetchJsonp();
return that.listOfResults;
};
问题:
这是我定义 JSON API 类后调用的内容:
var myJSON = json.getJsonp();
console.log(myJSON);
因为它是异步的,它在回调函数被调用之前移动到控制台日志,导致 MYJSON
为 undefined
。我不确定如何以在继续之前运行回调的方式将我的代码菊花链在一起。
我试图模拟来自 How can I get this JSONP call to return a value? 的解决方案.我可能错过了一步,或者我可能对某些事情一无所知!任何有助于澄清这一点的帮助将不胜感激。提前谢谢你:)。
附言我想避免使用 JQuery 等...将其严格保留为原始 JavaScript 将是有益的。
最佳答案
I am not sure how I can daisy chain my code together in such a way where it runs the callback before moving on.
你不能那样做。您必须依赖回调。将 callback
参数添加到您的 jsonpRequest
构造函数,并在执行 setListOfResults(data)
后调用该回调。您可能还希望允许设置将在其中执行回调的 this
上下文。
jsonpRequest.prototype.processCallback = function(data){
alert(data);
that.setListOfResults(data);
that.callback.apply(that.context, [data]);
};
关于javascript - JSONP回调乱序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18961164/