[js]ajax-異源請求jsonp
阿新 • • 發佈:2018-02-02
create ati data send 就是 path llb allow cte
ajax請求-解放每次手動輸url
js的XMLHttpRequest對象
我們使用XMLHttpRequest對象來發送一個Ajax請求
用xhr發一個ajax請求
因為我是webstorm,因此自帶音響哈.
也就是這個接口 http://localhost:63343/web_learn/ajax/ajax/data.txt 可以被訪問到,這裏我們不手動訪問呢了,用ajax來訪問.
這裏我們用ajax來請求這個接口,並將內容打印到console口
<script> var xhr = new XMLHttpRequest(); //1.創建xhr對象 xhr.open('get', 'http://localhost:63343/web_learn/ajax/ajax/data.txt', true); //2.準備發起url,默認異步true xhr.onreadystatechange = function () { //3.回來的數據該怎麽處理? if (xhr.readyState === 4 && xhr.status === 200) { console.log(xhr.responseText); } }; xhr.send(null); //4.開始發射 </script>
同源訪問-簡寫url
<script> var xhr = new XMLHttpRequest(); xhr.open('get', 'data.txt', true);//這裏url可以簡寫哦,默認代表訪問源 xhr.onreadystatechange = function () { if (xhr.readyState === 4 && xhr.status === 200) { console.log(xhr.responseText); } }; xhr.send(null); </script>
異源訪問
這裏我們訪問 http://www.weather.com.cn/data/sk/101010100.html 這個接口
<script> xhr = new XMLHttpRequest(); xhr.open('get', 'http://www.weather.com.cn/data/sk/101010100.html', true); //跨站訪問不允許Access-Control-Allow-Origin' header xhr.onreadystatechange = function () { if (xhr.readyState === 4 && xhr.status === 200){ console.log(xhr.responseText); } }; xhr.send(null); </script>
ajax跨源訪問是不允許的, 瀏覽器不允許他這樣搞. 也是為了安全的緣故吧.
解決ajax異源請求
瀏覽器不允許ajax來跨源,但是運行link script img等標簽跨源.
借助script標簽來解決異源問題.
我們找了個接口
https://suggest.taobao.com/sug?code=utf-8&q=%E5%9B%B4%E5%B7%BE&callback=fn
發現clallback=xx 他返回你傳遞給他的, 可見後端獲取到了這個參數(query),然後作為一部分返回給前端
jsonp.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>jsonp</title>
</head>
<body>
<script>
//jsonp方式解決異源問題
function fn(data) {
console.log(data);
}
</script>
<script type="text/javascript"
src="https://suggest.taobao.com/sug?code=utf-8&q=%E5%9B%B4%E5%B7%BE&callback=fn"> //這裏fn其實是函數名, 返回結果fn(一坨data), 恰好觸發了頁面的fn函數
</script>
</body>
</html>
/getdata?callback=fn部分自己實現--nodejs實現這個接口
即實現傳什麽函數名,返回什麽
如傳fn返回fn(data), 傳func,返回func(data)
app.js 我們設置函數名為maotai,返回maotai(data)
var http = require('http'), //導入http url fs模塊
url = require('url'),
fs = require('fs');
s1 = http.createServer(function (req, res) {// 創建服務器
var urlObj = url.parse(req.url, true), // 接受req對象
pathname = urlObj['pathname'], // 取出req裏的pathname
query = urlObj['query']; //獲取參數 /getall?cb=maotai" 裏的cb
// 不同的.html .css 返回時候設置http head不同的mime類型
var reg = /\.(HTML|CSS|JS|JSON|TXT|ICO)/i; //正則判斷mime類型
if (reg.test(pathname)) {
var suffix = reg.exec(pathname)[1].toUpperCase();//mime統一大寫比對
var suffixMIME = null;
switch (suffix) {
case "HTML":
suffixMIME = 'text/html';
break;
case "JS":
suffixMIME = 'text/javascript';
break;
case "CSS":
suffixMIME = 'text/css';
break;
case "JSON":
suffixMIME = 'application/json';
break;
case "ICO":
suffixMIME = 'application/octet-stream';
break;
}
try {
con = fs.readFileSync('.' + pathname);
res.writeHead(200, {'content-type': suffixMIME + ';charset=utf-8'});
res.end(con);
} catch (e) {
res.writeHead(404, {'content-type': 'text/plain;charset=utf-8'});
res.end("file not found")
}
}
if (pathname === "/getall") {
var fnName = query["cb"]; //獲取cb=maotai
con = fs.readFileSync('./data.txt', 'utf-8');
con = 'a,b';
res.writeHead(200, {'content-type': 'application/json;charset=utf-8'});
res.end(fnName + '(' + con + ',22)'); // end即返回 maotai(a,b,22)
}
});
s1.listen(1234, function () {
console.log("http://127.0.0.1:1234/getall?cb=maotai");
});
啟動nodejs服務端
實現這個接口
http://127.0.0.1:1234/getall?cb=maotai
返回結果
觸發頁面
<script>
var a = 12;
var b = 13;
function maotai(a,b,num) {
console.log(a,b,num);
}
</script>
<!--//jsonp可以返回任意格式字符串,但一般返回的是json格式字符串-->
<script type="text/javascript" src="http://127.0.0.1:1234/getall?cb=maotai"></script>
訪問返會結果.
[js]ajax-異源請求jsonp