hsipeng / java_learnning_trip

spring springMVC mybatis
0 stars 1 forks source link

JQuery的AJAX #40

Open hsipeng opened 7 years ago

hsipeng commented 7 years ago
  document.getElementById("b1").onclick=function () {
    //AJAX调用
    /**
      创建xmlHttpRequest
      绑定回调函数
      与服务器建立连接
      发送数据
      回调函数处理相应的数据
    */
    var xmlhttp = createXMLHttpRequest();
    xmlhttp.onreadystatechange = function () {
      if(xmlhttp.readyState == 4){
        if(xmlhttp.status == 200){
          var callback = xmlhttp.responseText;
          alert(callback)
        }
      }
    }

    xmlhttp.open("POST","../servlet/AjaxServlet",true);
    xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
    xmlhttp.send("name=张三");

  }

  function createXMLHttpRequest() {

    try{
       // IE7+, Firefox, Chrome, Opera, Safari 浏览器执行的代码
     xmlhttp = new XMLHttpRequest();
    }catch(tryMS){
      try{
        //IE6, IE5 浏览器执行的代码
        xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
      }catch(otherMS){
        try{
          xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }catch(failed){
          xmlhttp = null;
          //无法获得xmlhttp对象

        }
      }
    }
    return xmlhttp;
  }
hsipeng commented 7 years ago

url 请求路径 data 请求参数,使用JSON串 callback 回调函数

无参数,get,有参数,post

  • .get(ur,[data],[callback],[type]) url 请求路径 data 请求参数,使用JSON串 callback 回调函数 type 类型
  • .post(ur,[data],[callback],[type]) url 请求路径 data 请求参数,使用JSON串 callback 回调函数 type 类型

数据转化为JSON串,所以返回类型为json,返回html无效