天天看點

jQuery-Ajax快捷方法簡介快捷方法(這些方法幫你用最少的代碼發送常見的Ajax請求。)

  • 簡介
  • 快捷方法(這些方法幫你用最少的代碼發送常見的Ajax請求。)
    • 一、load()
      • 概述
      • load(url, [data], [callback])
    • 二、jQuery.get()和jQuery.post()
      • (1)jQuery.get()
        • 概述:
        • jQuery.get(url, [data], [callback], [type])
      • (2)jQuery.post()
        • 概述:
        • jQuery.post(url, [data], [callback], [type])
    • 三、jQuery.getScript()和jQuery.getJSON()方法
      • (1)jQuery.getScript()
        • 概述
        • jQuery.getScript(url, [callback])
      • (2)jQuery.getJSON( )
        • 概述
        • jQuery.getJSON(url, [data], [callback])

簡介

  • AJAX 是與伺服器交換資料的技術,它在不重載全部頁面的情況下,實作了對部分網頁的更新。
  • Query 提供多個與 AJAX 有關的方法。
  • 通過 jQuery AJAX 方法,您能夠使用 HTTP Get 和 HTTP Post 從遠端伺服器上請求文本、HTML、XML 或 JSON 同時您能夠把這些外部資料直接載入網頁的被選元素中。

快捷方法(這些方法幫你用最少的代碼發送常見的Ajax請求。)

一、load()

概述

  • 載入遠端 HTML 檔案代碼并插入至 DOM 中。
  • 預設使用 GET 方式 - 傳遞附加參數時自動轉換為 POST 方式。jQuery 1.2 中,可以指定選擇符,來篩選載入的 HTML 文檔,DOM 中将僅插入篩選出的 HTML 代碼。文法形如 “url #some > selector”。請檢視示例。

load(url, [data], [callback])

  • url:類型: String。必需的URL參數規定您希望加載的URL
  • data:類型: PlainObject, String。可選的,向伺服器發送請求的Key/value參數,例如{name:”“,age:23}
  • callback(responseText, textStatus, XMLHttpRequest):類型: Function()。當請求成功後執行的回調函數。
    • responseTxt -包含調用成功時的結果内容
    • textStatus-包含調用的狀态:可能是”success”、”notmodifiend”、”error”、”timeout”、”abort” 或”parsererror” 中的一個,最長見的是:success成功;error錯誤
    • XMLHttpRequest-經過jQuery封裝的一XMLHttpRequest對象(保留其本身的所有屬性和方法)

有一個PHP檔案test.php

<?php
echo "hi 好久不見"
?>
           

擷取php檔案内容

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>ajax()-load()</title>
    <script src="http://www.jq22.com/jquery/jquery-1.7.1.js"></script>
</head>

<body>
    <h5>ajax傳回的資料:</h5>
    <p></p>
</body>
<script>
    //傳回的内容放入p中
    $("p").load("test.php?"+Math.random(),function(response,status,xhr){
    //    console.log(response);//列印傳回的内容
    //    console.log(status);//列印調用的狀态
    //    console.log(xhr);//列印XMLHttpRequest對象
        if(status=="error"){
            alert("請求失敗"+status+xhr.statusText)
        }

    })
</script>
</html>
           

二、jQuery.get()和jQuery.post()

兩種在用戶端和伺服器端進行請求–響應常用方法是:GET 和 POST。

GET基本上用于從伺服器獲得(取回)資料。注釋:GET方法可能傳回緩存資料。

POST也可用于從伺服器擷取資料。不過,POST方法不會緩存資料,并且常用于連同請求一起發送資料。

(1)jQuery.get()

概述:

通過遠端 HTTP GET 請求載入資訊。

這是一個簡單的 GET 請求功能以取代複雜 .ajax。請求成功時可調用回調函數。如果需要在出錯時執行函數,請使用 . a j a x 。 請 求 成 功 時 可 調 用 回 調 函 數 。 如 果 需 要 在 出 錯 時 執 行 函 數 , 請 使 用 .ajax。

jQuery 1.12 中 jQuery.post 和 jQuery.get 支援對象參數,這樣一來好處還比較多,比如設定回調函數的context,或者跨域 post 時可以withCredential: true。

jQuery.get(url, [data], [callback], [type])

  • url:待載入頁面的URL位址
  • data:待發送 Key/value 參數。
  • callback:載入成功時回調函數。
  • type:傳回内容格式,xml, html, script, json, text, _default。

這是一個Ajax功能的縮寫,這相當于:

$.ajax({
  url: url,
  data: data,
  success: success,
  dataType: dataType
});
           

success 回調函數會傳入傳回的資料,是根據MIME類型的響應,它可能傳回的資料類型包括XML根節點, 字元串, JavaScript 檔案, 或者 JSON 對象。 同時還會傳入描述響應狀态的字元串。

執行個體(取php中的内容):

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>ajax()_get()</title>
    <script src="http://www.jq22.com/jquery/jquery-1.7.1.js"></script>
</head>
<body>
    <h5>ajax傳回的資料:</h5>
    <p>     </p>
</body>
<script>
    $.get("test.php?"+Math.random(),function(date,status,shr){
        $("p").append(date+"<br/>");
        $("p").append(status+"<br/>");
        $("p").append(shr.readyState);
    })
</script>
</html>
           

(2)jQuery.post()

概述:

  • 通過遠端 HTTP POST 請求載入資訊。
  • 這是一個簡單的 POST 請求功能以取代複雜

    $.ajax

    。請求成功時可調用回調函數。如果需要在出錯時執行函數,請使用

    $.ajax

    jQuery 1.12 中

    jQuery.post

    jQuery.get

    支援對象參數,這樣一來好處還比較多,比如設定回調函數的context,或者跨域 post 時可以withCredential: true。

jQuery.post(url, [data], [callback], [type])

  • url:發送請求位址。
  • data:待發送 Key/value 參數。
  • callback:發送成功時回調函數。
  • type:傳回内容格式,xml, html, script, json, text, _default。

示例:獲得 test.php 頁面傳回的 json 格式的内容:

$.post("test.php", { "func": "getNameAndTime" },
          function(data){
          alert(data.name); // John
          console.log(data.time); //  2pm
          }, "json");
           

三、jQuery.getScript()和jQuery.getJSON()方法

$.getScript

()和

$.getJSON()

方法專門用來加載JS/JSON檔案

(1)jQuery.getScript()

概述

  • 通過 HTTP GET 請求載入并執行一個 JavaScript 檔案。
  • jQuery 1.2 版本之前,getScript 隻能調用同域 JS 檔案。 1.2中,您可以跨域調用 JavaScript 檔案。注意:Safari 2 或更早的版本不能在全局作用域中同步執行腳本。如果通過 getScript 加入腳本,請加入延時函數。

jQuery.getScript(url, [callback])

  • url:待載入 JS 檔案位址。
  • callback:成功載入後回調函數。

    示例:動态加載新的官方jQuery 顔色動畫插件,一旦該插件加載完成就會觸發一些顔色動畫。

<!DOCTYPE html>
<html>
<head>
  <style>
.block {
   background-color: blue;
   width: px;
   height: px;
   margin: px;
}</style>
  <script src="https://code.jquery.com/jquery-latest.js"></script>
</head>
<body>

<button id="go">&raquo; Run</button>

<div class="block"></div>

<script>
(function() {
  var url = "https://raw.github.com/jquery/jquery-color/master/jquery.color.js";
  $.getScript(url, function() {
    $("#go").click(function(){
      $(".block")
        .animate( { backgroundColor: "rgb(255, 180, 180)" },  )
        .delay()
        .animate( { backgroundColor: "olive" },  )
        .delay()
        .animate( { backgroundColor: "#00f" },  );
    });
  });
})();
</script>

</body>
</html>
           

示例: 加載js檔案後改變寬

test.js檔案

$(".block").width();
           
<script>
    $("#go").click(function(){
         $.getScript("text.js");
    })
</script>
           

(2)jQuery.getJSON( )

概述

  • 通過 HTTP GET 請求載入 JSON 資料。
  • 在 jQuery 1.2 中,您可以通過使用JSONP形式的回調函數來加載其他網域的JSON資料,如 “myurl?callback=?”。jQuery 将自動替換 ? 為正确的函數名,以執行回調函數。 注意:此行以後的代碼将在這個回調函數執行前執行。

jQuery.getJSON(url, [data], [callback])

  • url:發送請求位址。
  • data:待發送 Key/value 參數。
  • callback:載入成功時回調函數。

重要提示: 從jQuery 1.4開始,如果JSON檔案包含一個文法錯誤,該請求通常會靜靜的失敗。是以應該避免頻繁手工編輯JSON資料。JSON文法規則比JavaScript對象字面量表示法更加嚴格。例如,所有在JSON中的字元串,無論是屬性或值,必須用雙引号括起來,更多JSON細節資訊請參閱http://json.org/ 。

示例:從 Flickr JSONP API中加載最近的四張标簽為貓的圖檔:

<!DOCTYPE html>
<html>
<head>
  <style>img{ height: px; float: left; }</style>
  <script src="https://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  <div id="images">

</div>
<script>
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?",
  {
    tags: "mount rainier",
    tagmode: "any",
    format: "json"
  },
  function(data) {
    $.each(data.items, function(i,item){
      $("<img/>").attr("src", item.media.m).appendTo("#images");
      if ( i ==  ) return false;
    });
  });</script>

</body>
</html>
           

繼續閱讀