[英]Specifying a callback in jQuery.ajax to OpenCalais SemanticProxy service
我正在尝试查询OpenCalais服务语义代理。 不幸的是,它们的url格式如下:
http://service.semanticproxy.com/processurl/APIKEY/jsonp:handler_function/http://en.wikipedia.org/wiki/Germany
注意函数回调,不在callback =中吗? 参数,而是遵循响应格式(jsonp :)。 这意味着我不能使用.getJSON,而需要使用.ajax方法。 所以我有以下对象定义:
function Subject() {
}
Subject.prototype.populate = function(page_title) {
var url = "http://service.semanticproxy.com/processurl/APIKEY/jsonp:handler/http://en.wikipedia.org/wiki/" + page_title;
$.ajax({url: url, dataType: "script", type: "GET", cache: false, callback: null, data: null});
};
var handler = function (data) {
// do stuff with the returned JSON
};
s = new Subject();
s.populate("Germany");
这很好。 但是,我真正想做的是设置Subject对象的属性。 但是我不知道如何在Subject的上下文中创建一个可以用作回调的函数。 即:
Subject.prototype.handler = function(data) { this.title = data.title }
有任何想法吗?
您必须在window
对象上设置一个函数。 从本质上讲,(我认为)这就是jQuery使用.getJSON方法所做的事情。 以下内容有些古怪,但希望它可以为您指明正确的方向:
function Subject() {
}
Subject.prototype.populate = function(page_title) {
// Save context object
var subject = this;
// Create function name like subjectHandler1281092055198
var functionName = "subjectHandler" + new Date().getTime();
window[functionName] = function(data) {
// Invoke function with saved context and parameter
subject.handler.call(subject, data);
}
var url = "http://service.semanticproxy.com/processurl/APIKEY/jsonp:" + functionName + "/http://en.wikipedia.org/wiki/" + page_title;
$.ajax({url: url, dataType: "script", type: "GET", cache: false, callback: null, data: null});
};
Subject.prototype.handler = function (data) {
// do stuff with the returned JSON
};
s = new Subject();
s.populate("Germany");
我不认为您能够做到这一点,仅仅是因为JSONP的工作原理,看看它实际上是如何返回浏览器的,它几乎可以做到这一点:
<script type="text/javascript">
handler({ title: "Germany", ...other properties... });
</script>
这里无法维护参考,您一次只能执行一个请求,也可以为每个主题保留一个对象映射,但是无法在JSONP请求中进行。
对象映射如下所示:
//delcare this once for the page
var subjects = {};
//do this per subject
var s = new Subject();
s.populate("Germany");
subjects["Germany"] = s;
然后,在您的hanldler中,如果任何data
属性是"Germany"
,则可以通过这种方式获取它,例如:
var handler = function (data) {
var subject = subjects[data.title];
//subject is your Germany subject, use it, go nuts!
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.