zoukankan      html  css  js  c++  java
  • ajax的封装及调用(版本一)

    1.封装

    //封装秘诀:将相同的留下来,将不同的作为参数传递

    function ajax (type,url,async,param,handle200,handle404,handle500,loading){
    if(async == null){
    async = true;//默认使用异步
    }

    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function(){
    if(xhr.readyState == 4){
    if(xhr.status == 200){
    handle200(xhr)
    }else if(xhr.status == 404){
    handle404(xhr)
    } else if(xhr.status == 500){
    handle500(xhr)
    }
    }else{
    loading(xhr)
    }
    }

    if(type.toLowerCase() == "get"){
    if(param != null){
    xhr.open(type,url+"?"+param,async);
    }else{
    xhr.open(type,url,async);
    }
    xhr.send();
    }else if(type.toLowerCase() == "post"){
    xhr.open(type,url,async);
    xhr.setRequestHeader("content-type","application/x-www-form-urlencoded")
    xhr.send(param);
    }
    }


    2.在servlet中的设置

    //获取get方法的发送的数据
    System.out.println(request.getParameter("name"));
    System.out.println(request.getParameter("age"));

    try {
    Thread.sleep(5000);
    } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }

    //要返回数据,用流
    PrintWriter out = response.getWriter();
    out.write("{ "name" : "zhangsan" , "age" : 18 }");
    }

     

    3.调用
    function doAjax(){
    ajax("get","getdata",null,"name=zhangsan&age=20",function(xhr){
    var str = xhr.responseText;
    var obj = JSON.parse(str);
    console.log(obj.name);
    console.log(obj.age);
    },function(xhr){
    window.loaction.href = "404.html";
    },function(xhr){
    window.loaction.href = "500.html";
    },function(xhr){
    //数据加载中
    });
    }

     

  • 相关阅读:
    Java反射中Class.forName与classLoader的区别
    Java各种成员初始化顺序
    crontab python脚本不执行
    Java mybatis缓存(转)
    Java Synchronized及实现原理
    JVM类加载器
    SSH掉线问题
    SSH登陆远程卡、慢的解决的办法
    shell脚本执行python脚本时,python如何将返回值传给shell脚本
    使用scrapy进行数据爬取
  • 原文地址:https://www.cnblogs.com/su-chu-zhi-151/p/11224347.html
Copyright © 2011-2022 走看看