Ajax下
2018-09-22 本文已影响0人
追逐_e6cf
一、cors跨域请求
document.onclick = function(){
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://localhost:8080/", true);
xhr.send();
xhr.onreadystatechange = function(){
if(xhr.readyState == 4){
if((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304){
var message = xhr.responseText;
alert(message);
}
}
}
}
var http = require("http");
var arr = ["baidu.com", "taobao.com"];
http.createServer(function(req, res){
if(arr.indexOf(req.headers["origin"]) != -1){
res.setHeader("Access-Control-Allow-Origin", "*");
}
res.write("111");
res.end();
}).listen(8080)
二、jsonp
百度搜索的例子
var headEle = document.getElementsByTagName("head")[0];
document.onclick = function(){
var scriptEle = document.createElement("script");
scriptEle.src = "https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd=a&cb=fnShow";
headEle.appendChild(scriptEle);
}
function fnShow(json){
console.log(json.s);
}
jsonp.html
var headEle = document.getElementsByTagName("head")[0];
document.onclick = function(){
var scriptEle = document.createElement("script");
scriptEle.src = "http://localhost:8081/sum?a=4&b=38&callback=fnSum";
headEle.appendChild(scriptEle);
}
function fnSum(json){
alert(json);
}
jsonp.js
var http = require("http");
var url = require("url");
http.createServer(function(req, res){
var url_sum = url.parse(req.url, true).query;
var url_a = url_sum["a"];
var url_b = url_sum["b"];
var url_cb = url_sum["callback"];
res.write(url_cd +"(" + (url_a*1+url_b*1) + ")");
res.end()
}).listen(8001)