用nodejs实现json和jsonp服务
来源:互联网 发布:中国大数据公司排名 编辑:程序博客网 时间:2024/06/05 23:05
一、JSON和JSONP
JSONP的全称是JSON with Padding,由于同源策略的限制,XmlHttpRequest只允许请求当前源(协议,域名,端口)的资源。如果要进行跨域请求,我们可以通过使用html的script标记来进行跨域请求,并在相应中返回要执行的script代码,其中可以直接使用JSON传递javascript对象。这种跨域的通讯方式成为JSONP。
由此我们可以看出两者的区别:
json: 一种轻量级的数据格式。
jsonp:为实现跨域,而采用的一种脚本注入方法。
备注:要了解更多json,可以参见我原先写的一篇介绍json的文章:《JSON那些事》
二、实现
为了简单起见,我们要读取数据都是
var data = {'name': 'jifeng', 'company': 'taobao'};
1. 服务器端代码:
- var http = require('http');
- var urllib = require('url');
- var port = 10011;
- var data = {'name': 'jifeng', 'company': 'taobao'};
- http.createServer(function(req, res){
- var params = urllib.parse(req.url, true);
- console.log(params);
- if (params.query && params.query.callback) {
- //console.log(params.query.callback);
- var str = params.query.callback + '(' + JSON.stringify(data) + ')';//jsonp
- res.end(str);
- } else {
- res.end(JSON.stringify(data));//普通的json
- }
- }).listen(port, function(){
- console.log('server is listening on port ' + port);
- })
2. 游览器端代码,为方便起见,我直接用了jquery的方法
- <html>
- <head>
- <script src="http://code.jquery.com/jquery-latest.js"></script>
- <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
- </head>
- <body>
- <script type="text/javascript">
- function get_jsonp() {
- $.getJSON("http://10.232.36.110:10011?callback=?",
- function(data) {
- $('#result').val('My name is: ' + data.name);
- });
- }
- </script>
- <a href="javascript:get_jsonp();">Click me</a><br />
- <textarea id="result" cols="50" rows="3"></textarea>
- </body>
- </html>
0 0
- 用nodejs实现json和jsonp服务
- 用nodejs实现json和jsonp服务
- JSON和JSONP JSONP 实现跨域访问
- JSON和JSONP 实现跨域访问
- 【跨域Jsonp】是否可以用jsonp完成跨域? nodejs发布的服务可以
- JSON 和 JSONP
- JsonP和Json
- 说说JSON和JSONP
- JSON 和 JSONP
- JSON和JSONP
- JSON和JSONP
- 说说JSON和JSONP
- 说说JSON和JSONP
- 说说JSON和JSONP
- 说说json和jsonp
- json和jsonp
- 说说JSON和JSONP
- 说说JSON和JSONP
- 网络分层——OSI模型
- Android Intent应用,打开网页,安装程序,打电话,打开地图等功能
- h264 profile & level .
- AndroidManifest.xml之<supports-screens> manifest element详解
- 用两个栈实现队列 & 用两个队列实现栈
- 用nodejs实现json和jsonp服务
- RabbitMQ之基础概念
- JAVA ThreadPoolExecutor详解
- 余秋雨 成熟是一种明亮而不刺眼的光辉
- H.264(MPEG-4 AVC)级别(Level),DPB与MaxDpbMbs详解 .
- VC++调用外部exe
- N!含有质因子2的个数
- Android学习系列--App列表之圆角ListView
- Android代码编写规范