1. 程式人生 > >jQuery-Ajax快捷方法

jQuery-Ajax快捷方法

簡介

  • 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調調使.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.postjQuery.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: 150px;
   height: 70px;
   margin: 10px;
}</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)" }, 1000 )
        .delay(500)
        .animate( { backgroundColor: "olive" }, 1000 )
        .delay(500)
        .animate( { backgroundColor: "#00f" }, 1000 );
    });
  });
})();
</script>

</body>
</html>

示例: 載入js檔案後改變寬 test.js檔案

$(".block").width(50);
<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: 100px; 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 == 3 ) return false;
    });
  });</script>

</body>
</html>