2018年1月14日 星期日

(JS)Cross Domain Ajax 跨網域抓取資料

試著抓取
http://data.ntpc.gov.tw/api/v1/rest/datastore/382000000A-000077-002
都失敗 原因出在瀏覽器不允許cross domain抓取資料
因為會有安全問題middle in attack(中間人攻擊)

Chrome extension plugin:Allow-Control-Allow-Origin: *
外掛:https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=zh-TW
外掛原文:
Allows to you request any site with ajax from any source. Adds to response 'Allow-Control-Allow-Origin: *' header
Developer tool.

*Summary*
Add to response header rule - 'Access-Control-Allow-Origin: *'

*Hint*
Same behavior you can get just using chrome flags [http://www.chromium.org/dJSevelopers/how-tos/run-chromium-with-flags]

chrome --disable-web-security

or

--allow-file-access-from-files --allow-file-access --allow-cross-origin-auth-prompt

簡單來說就是一個開關都設好了
Now:Test on jsfiddle


JS with jquery

1
2
3
4
5
6
//Enable cross domain function only
var site = "http://data.ntpc.gov.tw/api/v1/rest/datastore/382000000A-000077-002";
  $.getJSON( site, function(data) {
  //html with json to string
  $("#result").html( JSON.stringify(data) );
});

0 意見: