老师对于浏览器跟服务器的数据通信有点懵,我的理解对吗?

来源:4-1 初识跨域

要每天学习的小蓝同学

2021-06-25 19:44:10

理解一:

相关代码:

 <script>
const url = 'https://www.imooc.com/api/http/search/suggest?words=js&age=18';
// 创建xhr对象
const xhr = new XMLHttpRequest();
// 监听事件,处理响应
xhr.onreadystatechange = () => {
if (xhr.readyState !== 4) return;

if ((xhr.status >= 200 && xhr.status < 300) || xhr.status === 304) {
console.log(xhr.responseText);
console.log(typeof xhr.responseText);
}
}
// 准备发送请求open()
xhr.open('GET', url, true);
// 发送请求
xhr.send(null);
</script>

准备发送这里携带的数据给服务器

 const url = 'https://www.imooc.com/api/http/search/suggest?words=js&age=18';
// 准备发送请求open()
xhr.open('GET', url, true);
// 发送请求
xhr.send(null);

然后对服务器响应回来做监听

// 监听事件,处理响应
xhr.onreadystatechange = () => {
if (xhr.readyState !== 4) return;

if ((xhr.status >= 200 && xhr.status < 300) || xhr.status === 304) {
console.log(xhr.responseText);
console.log(typeof xhr.responseText);
}
}

返回的数据显示在

console.log(xhr.responseText);

理解二:

相关代码:

<script>
const xhr = new XMLHttpRequest();
xhr.onreadystatechange = () => {
if (xhr.readyState != 4) return;
if ((xhr.status >= 200 && xhr.status < 300) || xhr.status === 304) {
console.log(xhr.responseText);
}
};
//在此补充代码
// json的简单值形式就对应着js中的基础数据类型
// xhr.open('GET','./plain.json',true);
// json的对象形式就对应着js中的对象
// xhr.open('GET','./obj.json',true);

// json的数组形式就对应着js中的数组
xhr.open('GET','./arr.json',true);

xhr.send(null);
</script>

其实就是从这里

 // json的数组形式就对应着js中的数组
xhr.open('GET','./arr.json',true);

'./arr.json'

获取数据发送到服务器,再服务器返回来给我们数据显示在

xhr.responseText

总的理解就是,虽然是简单的发送js中数据给服务器再获得回来显示出来,进一步说就是前段把数据发送给服务器保存,比如发送了1/2/3/4/5,我们想要1/2/3这几个数就提取就可以了,就是服务器返回的响应进行监听

写回答

2回答

好帮手慕慕子

2021-06-26

同学你好,整体理解是对的,很棒!!!祝学习愉快~

0

慕粉0644535011

2021-12-06

同学,1/2/3/4/5的例子是什么意思啊?有点懵,可以麻烦解释下吗

0

0 学习 · 15276 问题

查看课程