AJAX:他可以不用重新網頁,就可以跟後端資料庫PHP撈資料

ex : search/ login

透過XMLHttpRequest()實作

  • open('格式get讀取資料/post傳送資料','讀取網址,''非同步/同步')
  • send(值)
var xhr= new XMLHttpRequest();
xhr.open('get','https://hexschool.github.io/ajaxHomework/data.json',true)
xhr.send(null)

非同步/同步

  • true 非同步:不會把資料傳回來,就讓程式繼續跑下去,等到回傳才會自動回傳

  • 時機:因為VUE RECT 關係,大部分都是以true

  • 實驗結果:TRUE 撈不到資料

  • false 同步:˙他等資料傳回來,才讓程式碼繼續往下跑

readyState(偵測你的AJAX的狀態)

0 --你已經產生一個XMLHttpRequest但是還沒有連結到你要的資料

1--你用了open(),但你還沒有把資料傳送過去

2--偵測到你有用 send

3--loading

4--你撈到資料了,數據已經完全接受到

onload時機

當我確認有跑完的時候也就是資料有回傳到,才執行事件

xhr.onload = function(){console.log(xhr.responseText)}

xhr.status狀態

參考http狀態碼

遠端下載JSON

1.建立一個xmlhttprequester
2.傳送到對方SERVER資料
3.回傳資料到自己的browser
4.拿到資料怎麼處理

cross-oragin resourse sharing(CROS)

跨網域撈取資料阻擋=>先去測試test-cors.org看網站是否有開啟(status)

JSONP進行跨網域查詢(解決CROS)

  • html增加script你的資料+callback=function,可以去Chrome network查詢

  • 如果你要撈對方的 JSON 資料時,,使用 JSONP 去撈還是有可能無法撈到,原因是 後端工程師是必須針對 JSON 格式進行程式設計,才有辦法讓開發者用 callback 讀取。

  • 所以當對方網址沒開放 CORS,你又用 JSONP 去撈取也撈不到時,便代表他沒支援 JSONP

  • 只能做get不能post

  • CORS 為主,JSONP 已經不是目前主流,

<script src="資料網址&callback=getData"></script>
function getData(str) {
 console.log(str);
 //str就是資料網站的資料
}

Post

傳統式表單傳送資料

<form action="index.html">
    <input type="text" name="account">
    <input type="text" name="password">
    <input type="submit" value="submit">
</form>
網址
index.html?account=21312312&password=21321312
xxxxxy?資料=213&資料=123213

ajax post資料

var xhr =new XMLHttpRequest();
xhr.open('post','https://hexschool-tutorial.herokuapp.com/api/signup',true);
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");//傳統表單格式
xhr.send('[email protected]&password=123213213');

JSON-Ajax

var account = {
    email: '[email protected]',
    password:'1234'
}
var xhr = new XMLHttpRequest();
xhr.open('post','https://hexschool-tutorial.herokuapp.com/api/signup',true);
xhr.setRequestHeader('Content-type','application/json');
var data = JSON.stringify(account); //轉字串
xhr.send(data);

實務設計流程

1.queryselector/ addeventlistener
2.執行fun
讀取html值
興建 abc  object
object裡面塞值空變數
3.xhr
4.xhr判斷

results matching ""

    No results matching ""