您的位置:首页 > Web前端 > JavaScript

jq ajax 和js ajax 两种方式请求数据

2017-10-13 15:26 302 查看

jquery:

 (function getCoupon(code, time) {
       var ajax = jQuery.ajax({
           type: "post",
           url: '请求地址',
           data: {key: '&L!!VGKrJYGDgdfFhtLq', code: code, time: time},
           dataType: 'json',       //返回数据类型

           contentType: "application/json; charset=utf-8",   //请求数据编码类型

           success: function (data) {
               console.log(data);
               if (data === 'not_begin') {
                   return false;
               } else if(data === 1) {
                   jQuery("#Coupon_code").show();
                   jQuery("#free_au").text(code);
               } else {
                   jQuery("#Coupon_expired").show();
               }
           }
       });
       ajax.done(function(){
           console.log(ajax);
       });

   })('code2','2017-10-11 24:00:00');

javascript:

  var getCoupon = function(code,time){
       // var data = {key:'&L!!VGKrJYGDgdfFhtLq',code:code,time: time};
       var xmlHttpRequest = null; 
       if(window.XMLHttpRequest) {  
           xmlHttpRequest = new XMLHttpRequest();  
       } else {  
           if(window.ActiveXObject) {  
               try {//IE5、6  
                   xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");  
               } catch(e) {  
                   try {  
                       xmlHttpRequest = new ActiveXObject("Msxml2.XMLHTTP");  
                   } catch(e) {}  
               }  
           }  
       }
       xmlHttpRequest.onreadystatechange = function () {
           if (xmlHttpRequest.readyState == 4) {
             if (xmlHttpRequest.status == 200) {
               //200代表成功了
               console.log(xmlHttpRequest);
               if (xmlHttpRequest.data === 'not_begin') {
                   return false;
               } else if(xmlHttpRequest.data === 1) {
                   document.getElementById("Coupon_code").style.display = "block";
                   document.getElementById("free_au").innerText = code;
               } else {
                   document.getElementById("Coupon_expired").style.display = "block";
               }
             } else {
               alert("服务器返回错误!");
             }
           }
       };
         xmlHttpRequest.open('POST', 'url', true);
         xmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); 
         xmlHttpRequest.send('key=\&L!!VGKrJYGDgdfFhtLq&code=' + code + '&time=' + time);
   };
   getCoupon('code2','2017-10-11 11:00:00');
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  js ajax html javascript jq