1. 程式人生 > 程式設計 >原生js實現ajax請求和JSONP跨域請求操作示例

原生js實現ajax請求和JSONP跨域請求操作示例

本文例項講述了原生js實現ajax請求和JSONP跨域請求。分享給大家供大家參考,具體如下:

直接上程式碼:

const ajax = (params = {}) => {
 const nowJson = params.jsonp ? jsonp(params) : json(params);
 function jsonp(params){
  //建立script標籤並加入到頁面中
  var callbackName = params.jsonp;
  var head = document.getElementsByTagName('head')[0];
  // 設定傳遞給後臺的回撥引數名
  params.data['callback'] = callbackName;
  var data = formatParams(params.data);
  var script = document.createElement('script');
  head.appendChild(script);
 
  window[callbackName] = function(jsonData) {
   head.removeChild(script);
   clearTimeout(script.timer);
   window[callbackName] = null;
   params.success && params.success(jsonData);
  };
  //console.log(window[callbackName])
  //console.log(params.url + '?' + data)
 
  //url形式傳參
  //說明:下面的script載入資源後會返回一個自執行函式:[callbackName](responseData),這個形式就是去執行一個函式,函式的名字是一個引數
  //      同時在windows物件上定義了這個函式:[callbackName] = function(responseData){},這時就會呼叫這個函式
  script.src = params.url + '?' + data;
 
  //為了得知此次請求是否成功,設定超時處理
  if(params.time) {
   script.timer = setTimeout(function() {
    window[callbackName] = null;
    head.removeChild(script);
    params.error && params.error({
     message: '超時'
    });
   },params.time);
  }
 }
 //格式化引數
 function formatParams(data) {
  var arr = [];
  for(var name in data) {
   arr.push(encodeURIComponent(name) + '=' + encodeURIComponent(data[name]));
  };
 
  // 新增一個隨機數,防止快取
  arr.push('v=' + random());
  return arr.join('&');
 }
 
 // 獲取隨機數
 function random() {
  return Math.floor(Math.random() * 10000 + 500);
 }
 function json(params) {
  // 請求方式,預設是GET
  params.type = (params.type || 'GET').toUpperCase();
  // 避免有特殊字元,必須格式化傳輸資料
  params.data = formatParams(params.data);
  var xhr = null;
 
  // 例項化XMLHttpRequest物件
  if(window.XMLHttpRequest) {
   xhr = new XMLHttpRequest();
  } else {
   // IE6及其以下版本
   xhr = new ActiveXObjcet('Microsoft.XMLHTTP');
  };
 
  // 監聽事件,只要 readyState 的值變化,就會呼叫 readystatechange 事件
  xhr.onreadystatechange = function() {
   // readyState屬性表示請求/響應過程的當前活動階段,4為完成,已經接收到全部響應資料
   if(xhr.readyState == 4) {
    var status = xhr.status;
    // status:響應的HTTP狀態碼,以2開頭的都是成功
    if(status >= 200 && status < 300) {
     var response = '';
     // 判斷接受資料的內容型別
     var type = xhr.getResponseHeader('Content-type');
     if(type.indexOf('xml') !== -1 && xhr.responseXML) {
      response = xhr.responseXML; //Document物件響應
     } else if(type === 'application/json') {
      response = JSON.parse(xhr.responseText); //JSON響應
     } else {
      response = xhr.responseText; //字串響應
     };
     // 成功回撥函式
     params.success && params.success(response);
    } else {
     params.error && params.error(status);
    }
   };
  };
 
  // 連線和傳輸資料
  if(params.type == 'GET') {
   // 三個引數:請求方式、請求地址(get方式時,傳輸資料是加在地址後的)、是否非同步請求(同步請求的情況極少);
   xhr.open(params.type,params.url + '?' + params.data,true);
   xhr.send(null);
  } else {
   xhr.open(params.type,params.url,true);
   //必須,設定提交時的內容型別
   xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded; charset=UTF-8');
   // 傳輸資料
   xhr.send(params.data);
  }
 }
}
export default ajax;

呼叫:

ajax({
   jsonp:'JSONP',url:'http://localhost:8080/test',data:{},time:1000,success:function(data){
    console.log(data)
   },error:function(error){
    console.log(error)
   }
  })

更多關於JavaScript相關內容感興趣的讀者可檢視本站專題:《JavaScript中ajax操作技巧總結》、《JavaScript錯誤與除錯技巧總結》、《JavaScript資料結構與演算法技巧總結》、《JavaScript遍歷演算法與技巧總結》及《JavaScript數學運算用法總結》

希望本文所述對大家JavaScript程式設計有所幫助。