一、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();" rel="external nofollow" >Click me</a><br /> <textarea id="result" cols="50" rows="3"></textarea> </body> </html>
jquery中getJSON()方法可以參見:http://www.w3school.com.cn/jquery/ajax_getjson.asp
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答