小工具知识网

当前位置: 首页 > 行业知识 > Ajax学习

行业知识

Ajax学习

2026-11-28 08:04:00 来源:互联网转载

具体���板可参考:域名正在测试,该地址临时使用密码(He371226)内部的AJAX文件

所有的使用原生发起请求的均已创建XMLHttpRequest对象为xhr

var xhr = new XMLHttpRequest()

导入axios,jQuery,bootstrap需自行导入

XMLHttpRequest

原生JS发起GET请求

            xhr.open('GET', 'http://www.liulongbin.top:3006/api/getbooks')            xhr.send()            xhr.onreadystatechange = function () {                console.log(xhr.responseText);            }

原生JS发起POST请求

            xhr.open('POST', 'http://www.liulongbin.top:3006/api/addbook')            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')            xhr.send('bookname=你好&author=haha&publisher=中国')            xhr.onreadystatechange = function () {                if (xhr.readyState = 4 && xhr.status == 200) {                    console.log(xhr.responseText);                }            }

 jQuery

用jQuery发起get请求(无参数)

    $.get('http://www.liulongbin.top:3006/api/getbooks', function (res) {        console.log(res.data);    })

用jQuery发起get请求(有参数)

    $.get('http://www.liulongbin.top:3006/api/getbooks', { id: 1 }, function (req) {                console.log(req.data);        })

用jQuery发起post请求

$.post('http://www.liulongbin.top:3006/api/addbook', { bookname: '中国历史', author: '中国人民', publisher: '中国出版社' },        function (res) {        console.log(res);        }    )

用jQuery发起ajax(post)请求

        $('#ajaxPost').on('click', function () {            $.ajax({                type: 'POST',                url: 'http://www.liulongbin.top:3006/api/addbook',                data: {                    bookname: '数据结构',                    author: '啦啦啦',                    publisher: '中国出版社'                },                success: function (res) {                    console.log(res);                }            })

用jQuery发起ajax(get)请求

            $.ajax({                type: 'GET',                url: 'http://www.liulongbin.top:3006/api/getbooks',                data: {                    id: 1                },                success: function (res) {                    console.log(res);                }            })

自行封装一个AJAX 

自行封装一个AJAX

//创建myajaxfunction resolveData(data){    var arr = []    for (var key in data){        var str =key+'='+data[key]        arr.push(str)    }    return arr.join('&')}function myajax(options){    var xhr=new XMLHttpRequest()    //把外界传来的参数对象转化为查询字符串    var qs=resolveData(options.data)    if(options.method.toUpperCase()==='GET'){        xhr.open(options.method,options.url+'?'+qs)        xhr.send()    }else if(options.method.toUpperCase()==='POST'){        xhr.open(options.method,options.url)        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')        xhr.send(qs)    }    xhr.onreadystatechange=function(){        if(xhr.readyState==4&&xhr.status==200){            var result=JSON.parse(xhr.responseText)            options.success(result)        }    }//调用myajax//GETmyajax({                method: 'GET',                url: 'http://www.liulongbin.top:3006/api/getbooks',                data: {                },                success: function (res) {                    console.log(res);                }            })//POSTmyajax({                method: 'POST',                url: 'http://www.liulongbin.top:3006/api/addbook',                data: {                    bookname: '哈哈哈',                    author: '啦啦啦',                    publisher: 'eqeq'                },                success: function (res) {                    console.log(res);                }            })        })

超时访问

 xhr.timeout = 30            xhr.ontimeout = function () {                alert('访问超时!')            }            xhr.open('GET', 'http://www.liulongbin.top:3006/api/getbooks')            xhr.send()            xhr.onreadystatechange = function () {                if (xhr.readyState == 4 && xhr.status == 200) {                    console.log(xhr.responseText);                }            }

formdata提交

直接由formdata提交

            //创建formdata            var fd = new FormData()            //通过append向fd中追加数据            fd.append('name', 'haha')            fd.append('upwd', '123456')            xhr.open('POST', 'http://www.liulongbin.top:3006/api/formdata')            //xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')            xhr.send(fd)            xhr.onreadystatechange = function () {                if (xhr.readyState == 4 && xhr.status == 200) {                    console.log(JSON.parse(xhr.responseText));                }            }

axios 

使用axios发起get请求

 var parmasObj = { name: 'zs', age: 20 }axios.get('http://www.liulongbin.top:3006/api/get', { params: parmasObj }).then(function (res) {    console.log(res.data);    }, function (err) { })

使用axios发起post请求

var dataObj = { location: '北京', address: '顺义' }axios.post('http://www.liulongbin.top:3006/api/post', dataObj).then(function (res) {                console.log(res.data);            }, function (err) { })

使用axios直接get请求

//get请求将数据写在params里

axios({    method: 'GET',    url: 'http://www.liulongbin.top:3006/api/get',    data: {    },    params: {    name: '钢铁侠',    age: 35    },}).then(function (res) {        console.log(res.data);    }, function (err) { })

使用axios直接post请求

//post请求将数据写在data里

axios({    method: 'POST',    url: 'http://www.liulongbin.top:3006/api/post',    data: {        location: '西安',        address: 'Xi`an University'    },    params: {    }}).then(function (res) {    console.log(res.data);}, function (err) { })

跨域

从一个根服务器访问另一个根服务器,受到浏览器保护会产生跨域,禁止访问,但是script标签的src属性可以来使用回调函数获得相应的值

原生jsonp 原理:利用script标签的src来使用回调函数获得相应的值

//?后面先为回调函数名称,然后是值function abc(data) {    console.log(data);}

Jquery jsonp 原理:jquery向header创建了一个script标签

$.ajax({            url: "http://www.liulongbin.top:3006/api/jsonp?name=haha&age=18",            //通过ajax发起jsonp请求必须指定 dataType: 'jsonp'            dataType: 'jsonp',            //自定义修改参数名,默认callback格式            //jsonp:'123',            //自定义修改回调函数名,默认jQueryxxxxxx格式            //jsonpCallback: 'haha',            success: function (res) {                    console.log(res);              }        })

表单

通过表单获取通过formData提交

HTML

                    通过表单获取通过formData提交                                    

JS

var form = document.querySelector('#form1')        form.addEventListener('submit', function (e) {            e.preventDefault()            var fd = new FormData(form)            xhr.open('POST', 'http://www.liulongbin.top:3006/api/formdata')            xhr.send(fd)            xhr.onreadystatechange = function () {                if (xhr.readyState == 4 && xhr.status == 200) {                    console.log(JSON.parse(xhr.responseText));                }            }        })

原生JS 文件上传(bootstrap)

HTML

        原生JS 文件上传服务器及显示和进度条                                                    上传文件        

JS

$('#btnUpload').on('click', function () {            var files = document.querySelector('#file1').files            if (files.length 对象 

JSON

 var jsonStr = '{"name":"jack","age":18,"id":123}'            var obj = JSON.parse(jsonStr)            var json1 = JSON.stringify({ name: 'marry', age: 16, id: 321 })            console.log(typeof obj);            console.log(obj);            console.log(typeof json1 + ':' + json1);

get请求序列化&反序列化

$('#jsonPost').on('click', function () {            xhr.open('GET', 'http://www.liulongbin.top:3006/api/getbooks')            xhr.send()            xhr.onreadystatechange = function () {                if (xhr.readyState == 4 && xhr.status == 200) {                    $.get('http://www.liulongbin.top:3006/api/getbooks', function (res) {                        console.log(res);                        var json2 = JSON.stringify(res)                        console.log(json2);                    })                    console.log(typeof xhr.responseText + ':' + xhr.response);                    console.log(JSON.parse(xhr.response));                }            }        })

URL编码

 var bian = encodeURI('你的')            var jie = decodeURI('%E4%BD%A0%E5%A6%88%E9%80%BC')            console.log(bian, jie);

上一篇:简明易懂教程,苹果APP下载操作指南,轻松学会下载技巧!

下一篇:西安网络推广公司专业解析,哪家公司最专业?