zoukankan      html  css  js  c++  java
  • ajax函数封装

    开发中有时要用到ajax,不可能每次都去ajax,所以就封装了ajax函数。该文不包括ajax的基础,如果有兴趣可以查看我的另外一篇文章ajax的工作原理http://www.cnblogs.com/salmonlin/p/8962777.html

    function ajax (method,url,data,success){  //四个参数,method是方法,url是路径,data是先后台传送的参数,success是后调函数
    var xhr = null;
    try{   //处理XMLHttpRequest对象的兼容性
    xhr = new XMLHttpRequest();
    }catch(e){
    xhr = new ActiveXObject("Microsoft.XMLHTTP");
    }
    if(method == 'get' && data){
    url += '?' + data;
    }
    xhr.open(method,url,true);
    if(method == 'get'){
    xhr.send();
    }
    else{
    xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    xhr.send(data);
    }

    xhr.onreadystatechange=function(){
    if ( xhr.readyState == 4 ) {

    if ( xhr.status == 200 ) {
    success && success(xhr.responseText);
    }
    else {
    alert('出错了,Err:' + xhr.status);
    }
    }
    }
    }

  • 相关阅读:
    Java WebSocket生命周期
    软件网络总结
    js模态弹窗
    spring boot
    spring aop
    lvs分布式
    如何在大牛面前装逼
    Java学习的思考
    javase知识点
    <nginx+PHP>nginx环境下配置支持php7
  • 原文地址:https://www.cnblogs.com/salmonlin/p/8962999.html
Copyright © 2011-2022 走看看