2011-06-05 55 views
0

我打了一下,與goo.gl API和Javascript:解析錯誤使用使用<a href="http://call.jsonlib.com/jsonlib-src.js" rel="nofollow">jsonlib</a>這樣jsonlib

function googl(url, cb) { 
    jsonlib.fetch({ 
     url: 'https://www.googleapis.com/urlshortener/v1/url?key=<my-api-key>', 
     header: 'Content-Type: application/json', 
     data: JSON.stringify({longUrl: url}) 
    }, function (m) { 
     var result = null; 
     try { 
      result = JSON.parse(m.content).id; 
      if (typeof result != 'string') { 
       result = null; 
      } 
     } catch (e) { 
      result = null; 
     } 
     cb(result); 
    }); 
} 

但是當我嘗試運行此,我得到這個錯誤:

ReferenceError: Can't find variable: jsonlib_cb_1307278663586 - fetch:1

fetch:1內容:

jsonlib_cb_1307278663587({"url": "https://www.googleapis.com/urlshortener/v1/url?key=<my-api-key>", "headers": {"via": "HTTP/1.1 GWA", "x-content-type-options": "nosniff", "x-google-cache-control": "remote-fetch", "expires": "Fri, 01 Jan 1990 00:00:00 GMT", "server": "GSE", "x-xss-protection": "1; mode=block", "etag": "\"0CNIIHrQYpIA69r1Pk9QCe1kzwI/u2pHqKdqG-dNhbJgEDlvIXi9lWk\"", "pragma": "no-cache", "cache-control": "no-cache, no-store, max-age=0, must-revalidate", "date": "Sun, 05 Jun 2011 13:14:52 GMT", "x-frame-options": "SAMEORIGIN", "content-type": "application/json; charset=UTF-8"}, "original-encoding": "iso-8859-1", "content": "{\n \"kind\": \"urlshortener#url\",\n \"id\": \"http://goo.gl/45cs\",\n \"longUrl\": \"http://developer.android.com/guide/practices/ui_guidelines/icon_design.html\"\n}\n"}) 

我需要做什麼改正這個?

PS:我已經移除代碼我的API密鑰將其公開,在我測試的API密鑰是存在的,它是正確的,因爲我可以看到有效的JSON,如果我點擊fetch:1上Safari調試器

+1

響應表明您實際上正在使用[JSONP](http://en.wikipedia.org/wiki/JSONP),您不應該解析它,但讓插入的腳本調用回調函數,解析參數。這是必要的,因爲您不能跨域發佈XMLHttpRequest。 – 2011-06-05 14:57:16

+0

@Marcel:但我該怎麼做? – 2011-06-05 15:20:01

回答

1

您忘記了將代理(本例中爲jsonlib.com)應該使用的方法設置爲POST,如required by the goo.gl API。在the documentation of JSONlib

看,你應該提供另一個屬性參數對象,method,如:

jsonlib.fetch({ 
    url: 'https://www.googleapis.com/urlshortener/v1/url', 
    header: 'Content-Type: application/json', 
    method: 'POST', 
    data: JSON.stringify({longUrl: url}) 
}, function (m) { 
    /* … */ 
}); 

現在m.content包含

'{ "kind": "urlshortener#url", "id": "http://goo.gl/ysEOJ", "longUrl": "http://tobyho.com/Trampolines_in_Javascript_and_the_Quest_for_Fewer_Nested_Callbacks" }' 

這是一個完全有效的JSON字符串。

相關問題