簡體   English   中英

在jQuery.ajax中為OpenCalais SemanticProxy服務指定回調

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM