javascriptJavaScript专题

JavaScript - GET/POST及跨域方法

2017-04-10  本文已影响265人  wwmin_
var apiURL = 'https://api.github.com/repos/vuejs/vue/commits?per_page=3&sha=';
var currentBranch='master';
var commits= null;
function fetchData() {
    var xhr = new XMLHttpRequest()
    var self = this
    xhr.open('GET', apiURL + self.currentBranch)
    xhr.onload = function () {
        self.commits = JSON.parse(xhr.responseText)
        console.log(self.commits[0].html_url)
    }
    xhr.send()
}

function fetchDataPost(){ 
       // unload 时尽量使用同步 AJAX 请求
       xhr("POST",{ 
            url: location.href, 
            sync: true, 
            handleAs: "text", 
            content:{ 
                param1:1 
            }, 
            load:function(result){ 
                 console.log(result); 
            } 
       }); 
  }; 
//window fetch方法
if (window.fetch && method == 'fetch') {
  let requestConfig = {
    credentials: 'include',
    method: type,
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json'
    },
    mode: "cors",
    cache: "force-cache"
  }

  if (type == 'POST') {
    Object.defineProperty(requestConfig, 'body', {
      value: JSON.stringify(data)
    })
  }

  try {
    var response = await fetch(url, requestConfig);
    var responseJson = await response.json();
  } catch (error) {
    throw new Error(error)
  }
  return responseJson
} else {
  let requestObj;
  if (window.XMLHttpRequest) {
    requestObj = new XMLHttpRequest();
  } else {
    requestObj = new ActiveXObject;
  }

  let sendData = '';
  if (type == 'POST') {
    sendData = JSON.stringify(data);
  }

  requestObj.open(type, url, true);
  requestObj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  requestObj.send(sendData);

  requestObj.onreadystatechange = () => {
    if (requestObj.readyState == 4) {
      if (requestObj.status == 200) {
        let obj = requestObj.response
        if (typeof obj !== 'object') {
          obj = JSON.parse(obj);
        }
        return obj
      } else {
        throw new Error(requestObj)
      }
    }
  }
}
//1.同源请求
$("#submit").click(function(){
  var data={
    name:$("name").val(),
    id:$("#id").val();
  };
  $.ajax({
    type:"POST",
    data:data,
    url:"http://localhost:3000/ajax/deal",
    dataType:"json",
    cache:false,
    timeout:5000,
    success:function(data){
      console.log(data);
    },
    error:function(jqXHR,textStatus,errorThrown){
      console.log("error"+textStatus+" "+errorThrown);
    }
  });
});

//node 服务器端3000 对应的处理函数为:
pp.post('/ajax/deal',function(req,res){
  console.log("server accept:",req.body.name,req.body.id)
  var data={
    name:req.body.name+'-server 3000 process',
    id:req.body.id+'-server 3000 process'
  };
  res.send(data);
  res.end();
})
//JSONP 是 JSON 的一种使用模式,可以解决主流浏览器的跨域数据访问问题。
//  其原理是根据 XmlHttpRequest 对象受到同源策略的影响,而 <script> 标签元素却不受同源策略影响,
//  可以加载跨域服务器上的脚本,网页可以从其他来源动态产生 JSON 资料。用 JSONP 获取的不是 JSON 数据,
//  而是可以直接运行的 JavaScript 语句。

//2.使用 jQuery 集成的 $.ajax 实现 JSONP 跨域调用
//回调函数
function jsonpCallback(data){
  console.log("jsonpCallback:"+data.name)
}
$("#submit").click(function(){
  var data={
    name:$("#name").val(),
    id:$("#id").val();
  };
  $.ajax({
    url:'http://localhost:3001/ajax/deal',
    data:data,
    dataType:"jsonp",
    cache:false,
    timeout:5000,
    //jsonp字段含义为服务器通过什么字段获取回调函数的名称
    jsonp:'callback',
    //声明本地回调函数的名称,jquery默认随机生成一个函数名称
    jsonpCallback:'jsonpCallback',
    success:function(data){
      console.log("ajax success callback:"+data.name)
    },
    error:function(jqXHR,textStatus,errorThrown){
      console.log(textStatus+''+errorThrown);
    }
  });
});
//服务器3001上对应的处理函数为
app.get('/ajax/deal',function(req,res){
  console.log("serer accept:");
  var data="{"+"name:"+req.query.name+"-server 3001 process',"+"id:'"+req.query.id+"-server 3001 process'"+"}";
  var callback=req.query.callback;
  var jsonp=callback+'('+data+')';
  console.log(jsonp);
  res.send(jsonp);
  res.end();
})
//请求头第一行为
GET /ajax/deal?callback=jsonpCallback&name=chiaki&id=3001&_=1473164876032 HTTP/1.1
//使用script标签原生实现JSONP
<script src = 'http://localhost:3001/ajax/deal?callback=jsonpCallback&name=chiaki&id=3001&_=1473164876032'></script>
function jsonpCallback(data){
  console.log("jsonpCallback:"+data.name)
}
//服务器 3000请求页面还包含一个 script 标签:
<script src = 'http://localhost:3001/jsonServerResponse?jsonp=jsonpCallback'></script>
//服务器 3001上对应的处理函数:
app.get('/jsonServerResponse', function(req, res) {
    var cb = req.query.jsonp
    console.log(cb)
    var data = 'var data = {' + 'name: $("#name").val() + " - server 3001 jsonp process",' + 'id: $("#id").val() + " - server 3001 jsonp process"' + '};'
    var debug = 'console.log(data);'
    var callback = '$("#submit").click(function() {' + data + cb + '(data);' + debug + '});'
    res.send(callback)
    res.end()
})
//CORS 的实现
//服务器 3000 上的请求页面 JavaScript 不变 (参考上面的同域请求)
//服务器 3001上对应的处理函数:
app.post('/cors', function(req, res) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By", ' 3.2.1')
    res.header("Content-Type", "application/json;charset=utf-8");
    var data = {
        name: req.body.name + ' - server 3001 cors process',
        id: req.body.id + ' - server 3001 cors process'
    }
    console.log(data)
    res.send(data)
    res.end()
})
// CORS 中属性的分析
//1.Access-Control-Allow-Origin
The origin parameter specifies a URI that may access the resource. The browser must enforce this. For requests without credentials, the server may specify “*” as a wildcard, thereby allowing any origin to access the resource.
//2.Access-Control-Allow-Methods
Specifies the method or methods allowed when accessing the resource. This is used in response to a preflight request. The conditions under which a request is preflighted are discussed above.
//3.Access-Control-Allow-Headers
Used in response to a preflight request to indicate which HTTP headers can be used when making the actual request.

// CORS 与 JSONP 的对比
//1.CORS 除了 GET 方法外,也支持其它的 HTTP 请求方法如 POST、 PUT 等。
//2.CORS 可以使用 XmlHttpRequest 进行传输,所以它的错误处理方式比 JSONP 好。
//3.JSONP 可以在不支持 CORS 的老旧浏览器上运作。

//一些其它的跨域调用方式
//1.window.name
//2.window.postMessage()
//参考:https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage
上一篇 下一篇

猜你喜欢

热点阅读