JavaScript -AJAX/FETCH GET/POST及跨域方法

  • xhr 原生方法請(qǐng)求
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 時(shí)盡量使用同步 AJAX 請(qǐng)求
       xhr("POST",{ 
            url: location.href, 
            sync: true, 
            handleAs: "text", 
            content:{ 
                param1:1 
            }, 
            load:function(result){ 
                 console.log(result); 
            } 
       }); 
  }; 
  • window fetch 方法
  async function Fetch({url, data, method, config}) {
    method = method.toUpperCase();
    //window fetch方法
    if (window.fetch) {
      let requestConfig = {
        credentials: 'include',
        method: method,
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json'
        },
        mode: "cors",
        cache: "force-cache"
      };

      function assignConfig(targetConfig, sourceConfig) {
        if (sourceConfig) {
          Object.keys(sourceConfig).forEach(key => {
            if (sourceConfig[key]) {
              if (typeof sourceConfig[key] !== "object") {
                if (sourceConfig[key]) Object.assign(targetConfig, sourceConfig)
              } else {
                assignConfig(targetConfig[key], sourceConfig[key])
              }
            }
          })
        }
      }

      assignConfig(requestConfig, config);
      if (method === '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 (method === 'POST') {
        sendData = JSON.stringify(data);
      }
      requestObj.open(method, url, true);
      if (config.headers) Object.keys(config.headers).forEach(key => {
        if (config.headers[key]) requestObj.setRequestHeader(key, config.headers[key])
      });
      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)
          }
        }
      }
    }
  }

  var baseUrl = "http://localhost:5000/api/";
  var loginUrl = "authentication/Login";
  var config = {
    headers: {
      Authorization: "Basic dXNlcm5hbWU6cGFzc3dvcmQ="
    }
  };
  Fetch({
    url: baseUrl + loginUrl,
    method: "post",
    data: {"Name": "wwmin", "password": "1"},
    config
  }).then(res => console.log(res));
  • 關(guān)于跨域
//1.同源請(qǐng)求
$("#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 服務(wù)器端3000 對(duì)應(yīng)的處理函數(shù)為:
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實(shí)現(xiàn)跨域調(diào)用
//JSONP 是 JSON 的一種使用模式,可以解決主流瀏覽器的跨域數(shù)據(jù)訪問(wèn)問(wèn)題。
//  其原理是根據(jù) XmlHttpRequest 對(duì)象受到同源策略的影響,而 <script> 標(biāo)簽元素卻不受同源策略影響,
//  可以加載跨域服務(wù)器上的腳本,網(wǎng)頁(yè)可以從其他來(lái)源動(dòng)態(tài)產(chǎn)生 JSON 資料。用 JSONP 獲取的不是 JSON 數(shù)據(jù),
//  而是可以直接運(yùn)行的 JavaScript 語(yǔ)句。

//2.使用 jQuery 集成的 $.ajax 實(shí)現(xiàn) JSONP 跨域調(diào)用
//回調(diào)函數(shù)
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字段含義為服務(wù)器通過(guò)什么字段獲取回調(diào)函數(shù)的名稱
    jsonp:'callback',
    //聲明本地回調(diào)函數(shù)的名稱,jquery默認(rèn)隨機(jī)生成一個(gè)函數(shù)名稱
    jsonpCallback:'jsonpCallback',
    success:function(data){
      console.log("ajax success callback:"+data.name)
    },
    error:function(jqXHR,textStatus,errorThrown){
      console.log(textStatus+''+errorThrown);
    }
  });
});
//服務(wù)器3001上對(duì)應(yīng)的處理函數(shù)為
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();
})
//請(qǐng)求頭第一行為
GET /ajax/deal?callback=jsonpCallback&name=chiaki&id=3001&_=1473164876032 HTTP/1.1
//使用script標(biāo)簽原生實(shí)現(xiàn)JSONP
<script src = 'http://localhost:3001/ajax/deal?callback=jsonpCallback&name=chiaki&id=3001&_=1473164876032'></script>
function jsonpCallback(data){
  console.log("jsonpCallback:"+data.name)
}
//服務(wù)器 3000請(qǐng)求頁(yè)面還包含一個(gè) script 標(biāo)簽:
<script src = 'http://localhost:3001/jsonServerResponse?jsonp=jsonpCallback'></script>
//服務(wù)器 3001上對(duì)應(yīng)的處理函數(shù):
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(跨域資源共享) 實(shí)現(xiàn)跨域調(diào)用
//CORS 的實(shí)現(xiàn)
//服務(wù)器 3000 上的請(qǐng)求頁(yè)面 JavaScript 不變 (參考上面的同域請(qǐng)求)
//服務(wù)器 3001上對(duì)應(yīng)的處理函數(shù):
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 的對(duì)比
//1.CORS 除了 GET 方法外,也支持其它的 HTTP 請(qǐng)求方法如 POST、 PUT 等。
//2.CORS 可以使用 XmlHttpRequest 進(jìn)行傳輸,所以它的錯(cuò)誤處理方式比 JSONP 好。
//3.JSONP 可以在不支持 CORS 的老舊瀏覽器上運(yùn)作。

//一些其它的跨域調(diào)用方式
//1.window.name
//2.window.postMessage()
//參考:https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 什么是跨域? 2.) 資源嵌入:、、、等dom標(biāo)簽,還有樣式中background:url()、@font-fac...
    電影里的夢(mèng)i閱讀 2,475評(píng)論 0 5
  • 瀏覽器在請(qǐng)求不同域的資源時(shí),會(huì)因?yàn)橥床呗缘挠绊懻?qǐng)求不成功,這就是通常被提到的“跨域問(wèn)題”。作為前端開(kāi)發(fā),解決跨域...
    SCQ000閱讀 2,764評(píng)論 1 52
  • 1. 什么是跨域? 跨域一詞從字面意思看,就是跨域名嘛,但實(shí)際上跨域的范圍絕對(duì)不止那么狹隘。具體概念如下:只要協(xié)議...
    w_zhuan閱讀 622評(píng)論 0 0
  • 看完這篇文章,你就知道我從幾個(gè)字自我介紹到3分鐘都經(jīng)歷了什么。 “XX,運(yùn)維”。 這是我聽(tīng)到過(guò)的最短的自我介紹,短...
    心理成長(zhǎng)小窩閱讀 4,897評(píng)論 3 6
  • 【1】 單位負(fù)責(zé)文印的有兩位姑娘。 忙起來(lái)的時(shí)候,好幾個(gè)科室都到他們辦公室催她們干活。雖然工作量大,但算起來(lái)兩個(gè)人...
    照進(jìn)來(lái)的光閱讀 154評(píng)論 0 0

友情鏈接更多精彩內(nèi)容