写篇文章让自己清楚Ajax——(3)Jquery请求使用

206 阅读1分钟

本篇文章没有过多的技巧,基于jq的文档提炼我们需要的ajax请求写法,帮助我们学习和巩固jq的常用api以及ajax请求的思想和语法。

Jquery的请求

Jquery作为dom库,内含了不少的ajax操作api,就算我们不去看jq写的代码我们也有必要学习这些知识承前启后,方能厚积薄发。

$.get()

$.get()有多种写法,并且都是get请求。

//前面部分写法不处理响应信息,第二种携带query参数进行get请求。
$.get('https://juejin.cn/column/7008169225663545381')
$.get('https://juejin.cn/column/7008169225663545381',{ name: "John", time: "2pm" })
//开始处理响应信息
$.get('https://juejin.cn/column/7008169225663545381',(data)=>{...})
$.get('https://juejin.cn/column/7008169225663545381',{ name: "John", time: "2pm" },
(data)=>{...})

四个参数: url:待载入页面的URL地址 data:待发送 Key/value 参数。 callback:载入成功时回调函数。 type:返回内容格式,xml, html, script, json, text, _default。

$.post()

$.post()都是post请求。

$.post('https://juejin.cn/column/7008169225663545381')
$.post('https://juejin.cn/column/7008169225663545381',{ name: "John", time: "2pm" })
//携带form表单信息,serialize用于处理form表单信息。
$.post("test.php", $("#testform").serialize());
//开始处理响应信息
$.post('https://juejin.cn/column/7008169225663545381',(data)=>{...})
$.post('https://juejin.cn/column/7008169225663545381',{ name: "John", time: "2pm" },
(data)=>{...})

参数和$.get()一致。

$.getJSON

getJSON默认完成

$.ajax

$.post()和$.get()都只有请求成功时执行回调函数,请求失败时则没办法处理。

.getJSON("url",(data)=>)//跨域就会使用jsonp.getJSON("url",(data)=>{})//跨域就会使用jsonp .ajax(options)