一、原生ajax
之前在学习ajax时,还弄了一个好玩的东西模拟百度搜索。也分享一下吧。
先简单地介绍一下ajax中的get和post方法吧
get方法
1.创建一个XMLHttpRequest类型对象
var xhr = new XMLHttpRequest();
兼容写法:(虽然现在通常不会用到)
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else {
xhr = new ActiveXObject("microsoft.XMLHTTP");
}
2.open()方法开启请求
接口是在JSONPlaceholder找的,open(方法,url)
xhr.open("GET", "https://jsonplaceholder.typicode.com/users?id=1");
3. send()方法发送请求
如果是get方法请求,不需要send中传参数,它如果想传参数,直接写在网址上就是上述的?id=1,
查找id为1的用户。
xhr.send(null);
4.指定回调函数,处理得到的数据
xhr.onreadystatechange = function () {
if (this.readyState === 4) {
console.log("请求成功");
}
}
通过判断xhr的readyState,确定此次请求是否完成。
if (this.readyState === 2) {
console.log("headers received", xhr.readyState);//headers received 2
} else if (this.readyState === 3) {
console.log("loading", xhr.readyState);//loading 3
console.log(xhr.responseText);
} else if (this.readyState === 4) {
console.log("done", xhr.readyState);//done 4
console.log(xhr.responseText);
}
//readyState === 3
{
"name": "harry",
"age": "19",
"id": 11
}
readyState === 4
{
"name": "harry",
"age": "19",
"id": 11
}
post
open()方法开启请求
xhr.open("POST", "https://jsonplaceholder.typicode.com/users")
设置请求头,一般get方法不需要设置,而post必须设置
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
设置参数,找到名字为harry年龄为19的用户
xhr.send("name=harry&age=19")
//也可以写成
xhr.send({
"name":"harry",
"age":19"
})
指定回调函数,处理得到的数据
这个和get一样
xhr.onreadystatechange = function () {
if (this.readyState === 4) {
console.log(xhr.responseText);
}
}
//结果
{
"name": "harry",
"age": "19",
"id": 11
}
二、jQuery中的ajax
就以post方法为例
$.ajax({
url: "http://localhost:3000/comments",//地址
type: "post",//方式
dataType: "json",//数据类型 有xml和json现在多位json
data: { "postId": 2, "content": "bad" },//参数
success: function (data) {//响应成功的回调方式
console.log(data);
}
})
这个 url是我用json-server创建的,类似于数据库。
而jquery中也有直接封装好的post了
$.post(url,参数,回调函数)
$.post("http://localhost:3000/comments", { "postId": 3, "content": "bad" }, function (data) {
console.log(data);
})
jquery中还封装了许多有用的方法如 更改数据 put,删除数据 delete,感兴趣的就自己去了解下吧。
三、模拟百度搜索
这是想要做成的样子:
html是这样的:
<div class="box">
<!-- 左边的框 -->
<div class="search-box">
<input type="text" class="txt">
<!-- 联想的数据会一li的形式出来 -->
<ul class="suggest-list">
</ul>
</div>
<!-- 搜索按键 -->
<input type="button" value="搜索" class="btn">
</div>
css就不贴上来了。
首先明确下步骤,接口还是就用原本百度的啦
1.添加一个txt中的按键弹起事件,每输入一个文字都会触发事件
2.发送请求,将输入框内的内容发送给后台
3. 获取需要的数组
4.将数组中数据渲染到页面中
代码我就不一步一步的敲了
var txt = $('.txt');
var ul = $('.suggest-list');
txt.keyup(function () {
//获取数据
var keyword = $(this).val();
// 发送请求
$.ajax({
url: 'https://www.baidu.com/sugrec?pre=1&p=3&ie=utf-8&json=1&prod=pc&from=pc_web',
dataType: 'jsonp',
jsonp: 'cb',
data: { 'wd': keyword },
success: function (data) {
// 获取需要的数组
var arr = data.g;
//将数组中数据渲染到页面中
if (keyword.length > 0) {
var str = '';
for (var i = 0; i < arr.length; i++) {
str += `<li>${arr[i].q}</li>`
}
ul.html(str)
} else {
// 搜索框没内容时,li不出现
ul.html('')
}
}
})
})
//点击其他地方联想内容消失
$(document).click(function () {
ul.html('')
})
效果展示:
当然实现效果也许有更简单的方法,欢迎来讨论(如果有人看的话qwq)
好了。溜了溜了。去弄个留言板来玩玩。