1.创建环境 cmd express
2.修改代码 app.js
/**
* Module dependencies.
*/
var express = require('express')
, routes = require('./routes')
, user = require('./routes/user')
, http = require('http')
, path = require('path');
var app = express();
app.configure(function(){
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
});
app.configure('development', function(){
app.use(express.errorHandler());
});
app.get('/', routes.index);
app.get('/users', user.list);
app.get('/jsonp',function(req,res,next){ #返回jsonp
res.jsonp({status:'jsonp'});
});
app.get('/json',function(req,res,next){ #返回json
res.jsonp({status:'json'});
});
http.createServer(app).listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
});
3.在public目录下新建,ajax.html
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<script type="text/javascript">
function get_jsonp() {
$.getJSON("http://127.0.0.1:3000/jsonp?callback=?", #跨域调用
function(data) {
$('#rjsonp').val('Jsonp info : ' + data.status);
});
}
function get_json(){ #Json调用
$.getJSON("json",
function(data) {
$('#rjson').val('Json info : ' + data.status);
});
}
</script>
<a href="javascript:get_jsonp();">Click me for jsonp</a><br />
<textarea id="rjsonp" cols="50" rows="3"></textarea>
<a href="javascript:get_json();">Click me for jsonp</a><br />
<textarea id="rjson" cols="50" rows="3"></textarea>
</body>
</html>
4.测试 输入网址http://127.0.0.1:3000/ajax.html
6 回复
jsonp的服务器回调函数,默认为callback,如果不取名字的时候,会随即生成 细节可参考 http://developer.51cto.com/art/201105/264791.htm?1364185021