Ajax程式設計 Ajax的基礎知識

2021-10-10 23:18:08 字數 4020 閱讀 9102

06.伺服器端響應的資料格式

07.請求引數的傳遞

08.獲取服務端響應的另一種方式

09.ajax錯誤處理

10.低版本瀏覽器的快取問題

11.同步非同步概述

12.ajax封裝

三、模板引擎

四、`formdata`物件

五、二進位制檔案

六、ajax請求限制

七、`$.ajax()`方法

八、restful api

九、xml基礎(略)

(1)建立ajax物件

(2)告訴ajax請求位址以及請求方式

xhr.

open

("請求方式"

,"請求位址"

);

(3)傳送請求
xhr.

send()

;

(4)獲取伺服器端給客戶端的相應資料
xhr.

onload

=function()

xhr.

onload=(

)=>

(1)get請求引數的傳遞(位址列)

(2)post請求引數的傳遞(請求體)

(3)請求引數的格式

name=ruovan&age=

24

還需要將json物件轉換為json字串,放在send()方法中,因為傳遞過程中,是以字串形式傳送的

json

.stringify

(json物件)

;

【注意】:get請求是不能提交json物件資料格式的,傳統**的表單提交也是不支援json物件資料格式的

xhr.readystate;

//獲取ajax狀態碼

// 當ajax狀態碼發生變化的時候觸發

xhr.

onreadystatechange=(

)=>

網路暢通,伺服器端沒有接收到請求,返回404狀態碼

網路暢通,伺服器端能接收到請求,伺服器端返回500狀態碼

網路中斷,請求無法傳送到務器端

解決方案:在請求位址的後面新增請求引數,保證每次請求中的請求引數的值不相同,這樣就不會從瀏覽器的快取中獲取資料

xhr.

open

("get"

,"請求位址?t="

= math.

random()

);

拼接資料

var html =

template

("tpl",)

;

將拼接好的html字串新增到頁面

document.

queryselector

("target"

).innerhtml = html

通過模板語法告訴模板引擎,資料和html字串如何拼接(使用方法同nodejs的模板語法)

"tpl" type=

"text/html"

>

}<

/section>

<

/script>

刪除

formdata.

delete

("屬性名"

);

追加

formdata.

("屬性名"

,"屬性值"

);

不同源的伺服器端請求位址寫在 script標籤的src屬性中

src屬性不受同源政策的影響,可以向非同源端傳送請求

伺服器端響應資料必須是乙個函式的呼叫,真正要傳送給客戶端的資料需要作為函式呼叫的引數

在客戶端全域性作用於下定義函式func,且需要放在script標籤前面

在函式內部對伺服器端返回的資料進行處理

**示例

函式名稱問題:客戶端和服務端需要一致

封裝jsonp函式

function

jsonp

(options)

// 動態建立script標籤

let script = document.

createelement

("script");

// 設定src屬性,並新增函式引數和請求資料

script.src = options.url +

"?callback="

+ funname + params;

// 加入頁面

let body = document.

queryselector

("#body");

body.

(script)

;// 刪除script標籤

script.

onload

=function()

}jsonp(,

success:

function()

})

語法示例

use(

(req,res,next)

=>);

語法示例:

xhr.withcredentials =

true

;

res.

header

("`access-control-allow-credentials"

,"true"

);

serialize方法

$.get()$.post()方法

$.

get(

"url",,

function

(response));

// 第二個引數是可選引數,用於傳遞資料

ajax全域性事件

// 當頁面中有ajax請求傳送時觸發

$(document).on

("ajaxstart"

,function()

);// 當頁面中有ajax請求完成時觸發(無論請求成功還是失敗)

$(document).on

("ajaxcomplete"

,function()

);

get:獲取資料

post:新增資料

put:更新資料

delete:刪除資料

get

("/xml"

,(req,res)

=>);

>

xhr.

onload

=function()

script

>

Ajax基礎知識

首先ajax的執行環境必須實在伺服器下的 首先需要建立乙個ajax物件var xhr new xmlhttprequest 告訴ajax物件以什麼方式傳送請求,要想哪傳送請求xhr.open get url 傳送請求xhr.send 獲取伺服器端響應客戶端的資料xhr.onload 使用get傳遞請...

AJAX基礎知識

新建xmlhttprequest物件 try catch error 開啟要傳送的位址通道 request.open get 位址,同步 非同步 給xmlhttprequest物件增加偵聽器,用來偵聽各種情況,包括各種鏈結狀態 request.addeventlistener load 偵聽函式 傳...

AJAX基礎知識學習筆記

下面就是在對ajax基礎學習的總結。注意 和樣式不能相容低版本ie 通過ajax獲取命中提示內容 document.getelementbyid keyword oninput function 操作發出請求 xhr.send 處理響應結果 建立物件 ie7 和其他瀏覽器都支援 xmlhttpreq...