我正在尝试查询OpenCalais服务semanticproxy.com。不幸的是,它们的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.prototype.handler = function(data) { this.title = data.title } 有什么想法吗?
发布于 2010-08-06 18:56:48
您必须在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");发布于 2010-08-06 18:39:48
我不认为你能够做到这一点,因为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;然后,在您的处理程序中,如果有任何data属性为"Germany",则可以通过这种方式获取它,例如:
var handler = function (data) {
var subject = subjects[data.title];
//subject is your Germany subject, use it, go nuts!
};https://stackoverflow.com/questions/3422938
复制相似问题