• 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){
    //数据加载中
    });
    }

     

  • 相关阅读:
    MyBatis进阶(一)
    git命令整理
    今天的任务--git练习
    深入浅出JavaScript(一)
    数据结构_树_二叉搜索树
    网络_体系结构
    数据结构_树
    算法_五大经典搜索算法
    SpringMVC入门
    spring 线程异步执行
  • 原文地址:https://www.cnblogs.com/su-chu-zhi-151/p/11224347.html
Copyright © 2020-2023  润新知