Created
December 26, 2011 01:32
Ajax, jquery JSONP call to node.js expressjs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<html> | |
<head> | |
<title>jsonp test</title> | |
<script src="http://code.jquery.com/jquery-1.6.2.min.js"></script> | |
<script type="text/javascript"> | |
$(function(){ | |
$('#select_link').click(function(e){ | |
e.preventDefault(); | |
console.log('select_link clicked'); | |
function test(data){ | |
return {"message":"ok"}; | |
} | |
$.ajax({ | |
dataType: 'jsonp', | |
data: "data=yeah", | |
jsonp: 'callback', | |
url: 'http://localhost:3000/endpoint?callback=?', | |
success: function(data) { | |
console.log('success'); | |
console.log(JSON.stringify(data)); | |
} | |
}); | |
}); | |
}); | |
</script> | |
</head> | |
<body> | |
<div id="select_div"><a href="#" id="select_link">Test</a></div> | |
</body> | |
</html> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var express = require('express'); | |
var app = express.createServer(); | |
app.use(express.bodyParser()); | |
app.get('/endpoint', function(req, res){ | |
var obj = {}; | |
obj.title = 'title'; | |
obj.data = 'data'; | |
console.log('params: ' + JSON.stringify(req.params)); | |
console.log('body: ' + JSON.stringify(req.body)); | |
console.log('query: ' + JSON.stringify(req.query)); | |
res.header('Content-type','application/json'); | |
res.header('Charset','utf8'); | |
res.send(req.query.callback + '('+ JSON.stringify(obj) + ');'); | |
}); | |
app.listen(3000); |
I was struggling about what to send to the callback function the whole evening!!! thanks a lot for posting it!!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I was struggling with this forever. This line
res.send(req.query.callback + '('+ JSON.stringify(obj) + ');');
made all the difference. Thanks for posting it.