在本身的服务器上传了一个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/... 记得给个★哈