在本身的服務器上傳了一個json文件:http://47.75.195.199/NodeApi/...
項目地址
https://github.com/chunsenye/...html
test.jsonnode
{ "a": "hello!", "b": "this", "c": "is", "d": "my", "e": "first", "f": "api" }
如今經過兩種方式請求它jquery
1. 在node環境中使用js代碼進行http請求 具體代碼以下git
getJson.jsgithub
//須要先按照request模塊 //npm i request var request = require('request'); // request(url,callback); request('http://47.75.195.199/NodeApi/test.json', function (error, response, data) { //若是請求成功則打印數據 不然顯示錯誤信息 if (!error && response.statusCode == 200) { console.log(data); }else { console.log(error); console.log(response.statusCode); } });
在改文件目錄下 運行 node getJson.js
請求成功 結果以下ajax
2.在html文件中的js代碼中進行http請求(ajax 和 jsonp)npm
getJson.htmljson
第一次嘗試 直接使用ajax 來 GET 請求數據centos
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>獲取json數據</title> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> </head> <body> <div id="json"></div> </body> <script> $.ajax({ type: "GET", url: 'http://47.75.195.199/NodeApi/test.json', success: function (response,data) { if (response.resultcode == 200) { console.log(data) } }, error: function (r) { console.log(r) } }) </script> </html>
獲得的結果是這樣的
這就是大名鼎鼎的跨域問題,咱們不能直接請求這個服務器上的數據 可是能夠經過jsonp 實現原理須要知道
第二次嘗試 加多了一行代碼 dataType: 'jsonp'api
<script> $.ajax({ type: "GET", url: 'http://47.75.195.199/NodeApi/test.json', dataType: 'jsonp', success: function (response,data) { if (response.resultcode == 200) { console.log(data) } }, error: function (r) { console.log(r) } }) </script>
獲得結果是 Uncaught SyntaxError: Unexpected token :
這裏是接口的數據不對,因此沒辦法獲取,若是要使用jsonp獲取 test.json應該這樣寫 加多一箇中括號
第三次嘗試
test.json
[{ "a": "hello!", "b": "this", "c": "is", "d": "my", "e": "first", "f": "api" }]
請求成功了,數據格式也對了,可是就是一直走error那裏,並不會執行成功的回調
第四次嘗試
<script> $.ajax({ type: "GET", url: 'http://47.75.195.199/NodeApi/test2.json', dataType: 'jsonp', jsonp: 'callback', jsonpCallback:"successCallback", success: function (response) { console.log('success:'+response) }, error:function(error){ console.log('error:'+error) } }).done(function(data){ console.log(data) }) </script>
仍是不行 說是還要改服務器,到這裏就很難受了,我剛買的阿里雲服務器 仍是centos系統的 目前還不知道如何解決 因此只能換一個連接 用別人的數據
更換連接:http://apis.juhe.cn/goodbook/...
這是我在聚合申請的一個接口 請求次數有限 天天只有一百次
最終請求成功,Chrome瀏覽器會攔截這樣的代碼 須要容許運行。
後面會處理服務器的問題,或許有人看到 也能夠指點一下我 。個人GitHub https://github.com/chunsenye/... 記得給個★哈