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

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

理解一:

相关代码:

 <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回答

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

慕粉0644535011 2021-12-06 15:01:54

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

问题已解决,确定采纳
还有疑问,暂不采纳

恭喜解决一个难题,获得1积分~

来为老师/同学的回答评分吧

0 星
请稍等 ...
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号

在线咨询

领取优惠

免费试听

领取大纲

扫描二维码,添加
你的专属老师