iT邦幫忙

0

用jquery ajax抓取跨網域json資料,出現Failed to load

以下是程式碼:

<button>catch</button>
<script>

    $('button').on('click',getJson);
    function getJson(){
        $.ajax({
                type:'GET',
               dataType: "json", url:'https://www.railway.gov.tw/Upload/UserFiles/%E8%87%BA%E9%90%B5%E5%B1%80%E6%88%BF%E5%9C%B0%E7%94%A2%E5%87%BA%E7%A7%9F%E6%83%85%E5%BD%A2.json',
            success:function(data){
                console.log(data);
            }
        
        });
    }
</script>

ajax.html:1 Failed to load https://www.railway.gov.tw/Upload/UserFiles/%E8%87%BA%E9%90%B5%E5%B1%80%E6%88%BF%E5%9C%B0%E7%94%A2%E5%87%BA%E7%A7%9F%E6%83%85%E5%BD%A2.json: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:65500' is therefore not allowed access.

問題到底出在哪裡呢? 請各位大大幫幫忙!

Allenci iT邦新手 5 級 ‧ 2018-05-28 23:43:29 檢舉
曾有邦友回答過我的問題跟你類似,請參考
https://ithelp.ithome.com.tw/articles/10094915

或google
"json cross domain"
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

2 個回答

0
純真的人
iT邦大師 1 級 ‧ 2018-05-29 18:00:16
最佳解答

如果你是要抓別人的網站的資料~
就只能用後端的語言來抓~
JQ只適合在允許有用Access-Control-Allow-Origin的網頁來抓~
畢竟JQ算前端語言~

1

一般是對方的 Access-Control-Allow-Origin 並不允許。
這樣會讓ajax無法跨域名運行。

其實碰上這種的,我會改換成用curl的方式來處理就行了。
然後再搭配ajax讀自已寫的curl就可以用了。

我要發表回答

立即登入回答