本篇内容主要讲解“ajax在js中和jQuery中的实例用法”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“ajax在js中和jQuery中的实例用法”吧!
目录
原生 JS
怎么发送一个 get 请求
怎么发送一个 post 请求
发送一个带有参数的 get 请求
发送一个带有参数的 post 请求
jQuery
$.get 几个参数,怎么使用
$.post 几个参数,怎么使用
$.ajax 几个参数,怎么使用
JSONP
原生 JS
怎么发送一个 get 请求
创建一个 ajax 对象
设置请求方式和请求地址[,是否异步]
准备接受请求体
发送请求
var xhr = new XMLHttpRequest()
xhr.open('get', '/ajax')
xhr.onload = function () {
console.log(xhr.responseText)
}
xhr.send(null)
怎么发送一个 post 请求
创建一个 ajax 对象
设置请求方式和请求地址[,是否异步]
准备接受请求体
发送请求
var xhr = new XMLHttpRequest()
xhr.open('post', '/ajax')
xhr.onload = function () {
console.log(xhr.responseText)
}
xhr.send(null)
发送一个带有参数的 get 请求
var xhr = new XMLHttpRequest
直接在请求地址后面拼接参数,? 开始,key=value 的形式,多个参数之间以 & 分割
xhr.onload = function () { console.log( xhr.responseText ) }
xhr.send()
发送一个带有参数的 post 请求
var xhr = new XMLHttpRequest
不需要在请求地址后面拼接任何内容
xhr.onload = function () { console.log( xhr.responseText ) }
post 方式携带参数是直接写在 xhr.send() 后面的 () 里面
自己收集数据 key=value
FormData 收集数据
var xhr = new XMLHttpRequest()
xhr.open('post', '/ajax')
xhr.onload = function () {
console.log(xhr.responseText)
}
xhr.setRequestHeadr('content-type', 'application/x-www-form-urlencoded')
xhr.send('key=value&key=value')
var fd = new FormData(document.querySelector('form'))
var xhr = new XMLHttpRequest()
xhr.open('post', '/ajax')
xhr.onload = function () {
console.log(xhr.responseText)
}
xhr.send(fd)
jQuery
$.get 几个参数,怎么使用
地址
$.post 几个参数,怎么使用
$.ajax 几个参数,怎么使用
JSONP
$.ajax 怎么发送 jaonp 请求
dataType 必须是 jsonp
方式必须是 get
jsonp: 根据后台来决定
$.ajax({
url: '/jsonp',
data: {},
dataType: 'jsonp',
jsonp: 'callback',
success (res) {
console.log(res)
}
})
到此,相信大家对“ajax在js中和jQuery中的实例用法”有了更深的了解,不妨来实际操作一番吧!这里是天达云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!