Ajax&Jquery

2019-04-29  本文已影响0人  hgzzz

Ajax

  1. Asynchronous Javascript And XML(异步JavaScript和XML)
    • 使用CSS和XHTML来表示。
    • 使用DOM模型来交互和动态显示。
    • 使用XMLHttpRequest来和服务器进行异步通信。
    • 使用javascript来绑定和调用。
  2. 作用:网络请求和局部刷新
  3. 简单使用
    • 创建异步对象,需要兼容IE
    function  getXmlHttp(){
      var xmlHttp;
      try{ // Firefox, Opera 8.0+, Safari
        xmlHttp=new XMLHttpRequest();
      }
      catch (e){
        try{// Internet Explorer
          xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch (e){
          try{
            xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
          }
          catch (e){}
        }
      }
    
      return xmlHttp;
    }
    
    • 发送 get 请求
    function get() {
        alert("ajax will send")
      // 1. 创建异步对象
      var xhr = ajaxFunction()
      // 2. 发送请求
      xhr.open("get", "/Servlet01?name=zhangsan&age=18", true)
    
      xhr.send();
    
      // 3. 获取响应数据
      xhr.onreadystatechange = function () {
          if(xhr.status == 200 &&  xhr.readyState == 4) {
            console.log(xhr.responseText)
          }
      }
    }
    
    • 发送post请求
    function post() {
      var xhr = new XMLHttpRequest()
    
      xhr.open("post", "/Servlet02", true)
      // 模拟表单提交
      xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
      xhr.send("name=zhangsan&age=18")
    
      xhr.onreadystatechange = function () {
          if (xhr.status = 200 && xhr.readyState == 4 ) {
              alert(xhr.responseText)
          }
      }
    }
    

Jquery使用Ajax

  1. load(url, [data], [callback]):载入远程 HTML 文件代码并插入至 DOM 中。
$("#ele").load(url, {key: value}, function(responseText, statusText, xhr){})
  1. jQuery.get(url, [data], [callback], [type])
    $.get("/servlet01", { name: "John" },function(data, status){
              alert(status + data);
    });
    
    • url:待载入页面的URL地址
    • data:待发送 Key/value 参数。
    • callback:载入成功时回调函数。
    • type:返回内容格式,xml, html, script, json, text, _default。
  2. jQuery.post(url, [data], [callback], [type])
    $.post("/servlet01", { key: value },
              function(data){
                alert(data.name); 
                console.log(data.age); 
              }, "json");
    
    • url:发送请求地址。
    • data:待发送 Key/value 参数。
    • callback:发送成功时回调函数。
    • type:返回内容格式,xml, html, script, json, text, _default。
  3. jQuery.ajax(url,[settings])
$.ajax({
   type: "POST",
   url: "/servlet",
   data: "name=John&age=18",
   success: function(msg){
     alert( "Data Saved: " + msg );
   }
});
上一篇 下一篇

猜你喜欢

热点阅读