饥人谷技术博客

ajax

2016-08-16  本文已影响198人  嘿菠萝

问答

代码题

1.封装一个 ajax 函数,能通过如下方式调用

<pre>
function ajax(opts){
var xmlhttp=new XMLHttpRequest();

  xmlhttp.onreadystatechange=function(){
    if(xmlhttp.readyState==4&&xmlhttp.status==200){  
    var json=JSON.parse(xmlhttp.responseText);
    opts.success(json);
    }
    if(xmlhttp.readyState==4&&xmlhttp.status==404){
     opts.error();
    }
  }
 var dataStr='';
 for(var key in opts.data){
  dataStr+=key+'='+opts.data[key]+'&';
 }

  dataStr = dataStr.substr(0,dataStr.length-1);
  if(opts.type.toLowerCase()==='post'){
     xmlhttp.open(opts.type,opts.url,true);
     xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
     xmlhttp.send(dataStr);
  }
 if(opts.type.toLowerCase()==='get'){
     xmlhttp.open(opts.type,opts.url+'?'+dataStr,true);
     xmlhttp.send();
  }

}

document.querySelector('#btn').addEventListener('click', function(){
ajax({
    url: 'getData.php',   //接口地址
    type: 'get',               // 类型, post 或者 get,
    data: {
        username: 'xiaoming',
        password: 'abcd1234'
    },
    success: function(ret){
        console.log(ret);       // {status: 0}
    },
    error: function(){
       console.log('出错了')
    }
})

});

</pre>

版权归吴秀芳和饥人谷所有,若有转载,请注明来源

上一篇 下一篇

猜你喜欢

热点阅读