不同的Ajax API 方案 备忘

在线PPT

/**
 * User: John Yu
 * Date: 2019-03-20
 * Time: 18:00
 */


/** 原生xhr **/
            function addBookWithXhr(){
                let xhr=new XMLHttpRequest();
                xhr.onreadystatechange=function () {
                    if(xhr.readyState==4){
                        if(xhr.status==201){
                            let book=JSON.parse(xhr.responseText);
                            console.log(book);
                        }
                    }
                }
                xhr.open("POST",url)
                //必须在open之后
                xhr.setRequestHeader('Content-Type','application/json')
                xhr.send('{"name":"mikeliu"}')
            }
            /** 全局fetch方法 **/
            function addBookWithFetch() {
                fetch(url,{
                    method:'POST',
                    headers:{'Content-Type':'application/json'},
                    body:JSON.stringify({name:'johnyu'})
                }).then(res=>res.json())
                    .then(book=>console.log(book))

            }
            /** JQuery **/
           function addBookWithJQuery(){
                $.ajax({url:url,type:"POST",
                    headers:{'Content-Type':'application/json'},
                    data:JSON.stringify({name:'tomli'}),
                    processData: false,
                    dataType:'json'
                }).then(function (book) {
                    console.log(book)
                })
            }
            /** Axios **/
            function addBookWithAxios(){
                axios({
                    url: 'http://localhost:3001/books',
                    method:'POST',
                    data:{name:'johnyu'}
                }).then(function (resp) {
                    console.log(resp.data.name)
                })
            }

            /**测试**/
            document
                .querySelector("#test")
                .addEventListener("click",function () {
                    addBookWithAxios();
                })
        }

你可能感兴趣的:(不同的Ajax API 方案 备忘)