GWT JSON跨站点请求失败

时间:2010-08-07 20:44:52

标签: javascript json gwt jsonp

我根据这里的教程Googles x-site

做了一切
    /**
   * Make call to remote server.
   */
  public native static void getJson(int requestId, String url,
      StockWatcher handler) /*-{
   var callback = "callback" + requestId;

   // [1] Create a script element.
   var script = document.createElement("script");
   script.setAttribute("src", url+callback);
   script.setAttribute("type", "text/javascript");

   // [2] Define the callback function on the window object.
   window[callback] = function(jsonObj) {
   // [3]
     handler.@com.google.gwt.sample.stockwatcher.client.StockWatcher::handleJsonResponse(Lcom/google/gwt/core/client/JavaScriptObject;)(jsonObj);
     window[callback + "done"] = true;
   }

   // [4] JSON download has 1-second timeout.
   setTimeout(function() {
     if (!window[callback + "done"]) {
       handler.@com.google.gwt.sample.stockwatcher.client.StockWatcher::handleJsonResponse(Lcom/google/gwt/core/client/JavaScriptObject;)(null);
     }

     // [5] Cleanup. Remove script and callback elements.
     document.body.removeChild(script);
     delete window[callback];
     delete window[callback + "done"];
   }, 1000);

   // [6] Attach the script element to the document body.
   document.body.appendChild(script);
  }-*/;

但它一直让我失望..所有其他方法也都写了..我只能理解为什么它每次都告诉我“无法检索JSON”(它告诉我处理程序的输入为空时)

顺便说一下我在谈论谷歌网站上的“3.从远程服务器请求数据”

1 个答案:

答案 0 :(得分:3)

我建议使用JsonpRequestBuilder,而不是所有这些JSNI代码 - 没有JSNI代码(可能只是一些覆盖类型),更容易调试等。

 String url = "http://www.google.com/calendar/feeds/developer-calendar@google.com/public/full" +
     "?alt=json-in-script";
 JsonpRequestBuilder jsonp = new JsonpRequestBuilder(); // No JSNI!
 jsonp.requestObject(url,
     new AsyncCallback<Feed>() { // Type-safe!
       public void onFailure(Throwable throwable) {
         // Easy to debug! (hopefully)
       }

       public void onSuccess(Feed feed) {
         // Success!
         }
       }
     });