透過 get
取得 AJAX
資料後,一定也會有資料要傳給後端,可以使用 post
。
假如目前有一個會員資料物件:
1 2 3 4
| var account = { email: 'name123@email.com', password: '123xxxx' }
|
方法跟取得 AJAX 很像,程式碼如下:
1 2 3 4 5
| var xhr = new XMLHttpRequest(); xhr.open("post", "https://hexschool-tutorial.herokuapp.com/api/signin", true); xhr.setRequestHeader("Content-type", "application/json"); var data = JSON.stringify(account); xhr.send(data);
|
在 console 中輸入 xhr 會看到收到資料的狀態:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| XMLHttpRequest {onreadystatechange: null, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …} onreadystatechange: null readyState: 4 timeout: 0 withCredentials: false upload: XMLHttpRequestUpload {onloadstart: null, onprogress: null, onabort: null, onerror: null, onload: null, …} responseURL: "https://hexschool-tutorial.herokuapp.com/api/signin" status: 200 statusText: "OK" responseType: "" response: "{"success":false,"result":{},"message":"此帳號不存在或帳號密碼錯誤"}" responseText: "{"success":false,"result":{},"message":"此帳號不存在或帳號密碼錯誤"}" responseXML: null onloadstart: null onprogress: null onabort: null onerror: null onload: null ontimeout: null onloadend: null __proto__: XMLHttpRequest
|