在浏览器执行js脚本的两种方式

简介: 【10月更文挑战第20天】本文介绍了在浏览器中执行HTTP请求的两种方式:`fetch`和`XMLHttpRequest`。`fetch`支持GET和POST请求,返回Promise对象,可以方便地处理异步操作。`XMLHttpRequest`则通过回调函数处理请求结果,适用于需要兼容旧浏览器的场景。文中还提供了具体的代码示例。

在浏览器执行js脚本的两种方式
15/100
发布文章
weixin_42551921
未选择文件

fetch请求get

在浏览器执行http请求,可以使用fetch函数;

fetch("url").then(response => response.text())
.then(data => console.log(JSON.parse(data)['status']))
.catch(error => console.error(error))

在这里插入图片描述
直接返回json数据:

fetch("url").then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error))

执行两次:

fetch("https://1.com").then(response = >response.json()).then(data = >{
   
    let items = data.data.doc_list;
    items.forEach(item = >{
   
        if (item.doc_status == '4') {
   
            fetch("https://1.com").then(response = >console.log(response)).
            catch(error = >console.error(error))
        }
    })
}).
catch(error = >console.error(error))

定义这个技术,模拟手动删除数据:

for (let index = 1; index < 100; index++) {
   
 for(var t = Date.now();Date.now() - t <= 3000;);
    fetch("https://1.com/nshop/doc/getlist?sub_tab=2&pn=" + index + "&rn=10&query=&main_status=2&time_range=&buyout_show_type=1").then(response = >response.json()).then(data = >{
   
        let items = data.data.doc_list;
        console.log(items);
        if ( !! items) {
   
            items.forEach(item = >{
   
                if (item.doc_status == '4') {
   
                    fetch("https:/1.com/user/submit/newdocdelete?doc_id_str=" + item.doc_id + "&skip_fold_validate=1").then(response = >console.log(response)).
                    catch(error = >console.error(error))
                }
            })
        }
    }).
    catch(error = >console.error(error))
}

fetch请求post

// jsonplaceholder.typicode.com是一个测试网站
fetch('https://jsonplaceholder.typicode.com/users', {
   
  method: 'POST',
  headers: {
   
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
   
    name: 'John Doe',
    email: 'johndoe@example.com',
  })
})
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error(error));

使用XMLHttpRequest

发起GET请求:

const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://jsonplaceholder.typicode.com/users');
xhr.onload = () => {
   
  if (xhr.status === 200) {
   
    console.log(xhr.responseText);
  } else {
   
    console.error(`Error: ${
     xhr.status}`);
  }
};
xhr.send();

发送POST请求:

const xhr = new XMLHttpRequest();
xhr.open('POST', 'https://jsonplaceholder.typicode.com/users');
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onload = () => {
   
  if (xhr.status === 201) {
   
    console.log(xhr.responseText);
  } else {
   
    console.error(`Error: ${
     xhr.status}`);
  }
};
xhr.send(JSON.stringify({
   
  name: 'John Doe',
  email: 'johndoe@example.com',
}));

fetch请求get
在浏览器执行http请求,可以使用fetch函数;

fetch(“url”).then(response => response.text())
.then(data => console.log(JSON.parse(data)[‘status’]))
.catch(error => console.error(error))

在这里插入图片描述
直接返回json数据:

fetch(“url”).then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error))

执行两次:

fetch("https://1.com").then(response = >response.json()).then(data = >{
let items = data.data.doc_list;
items.forEach(item = >{
if (item.doc_status == '4') {
fetch("https://1.com").then(response = >console.log(response)).
catch(error = >console.error(error))
}
})
}).
catch(error = >console.error(error))
定义这个技术,模拟手动删除数据:

for (let index = 1; index < 100; index++) {
for(var t = Date.now();Date.now() - t <= 3000;);
fetch("https://1.com/nshop/doc/getlist?sub_tab=2&pn=" + index + "&rn=10&query=&main_status=2&time_range=&buyout_show_type=1").then(response = >response.json()).then(data = >{
let items = data.data.doc_list;
console.log(items);
if ( !! items) {
items.forEach(item = >{
if (item.doc_status == '4') {
fetch("https:/1.com/user/submit/newdocdelete?doc_id_str=" + item.doc_id + "&skip_fold_validate=1").then(response = >console.log(response)).
catch(error = >console.error(error))
}
})
}
}).
catch(error = >console.error(error))
}
fetch请求post
// jsonplaceholder.typicode.com是一个测试网站
fetch('https://jsonplaceholder.typicode.com/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
name: 'John Doe',
email: 'johndoe@example.com',
})
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
使用XMLHttpRequest
发起GET请求:

const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://jsonplaceholder.typicode.com/users');
xhr.onload = () => {
if (xhr.status === 200) {
console.log(xhr.responseText);
} else {
console.error(Error: ${xhr.status});
}
};
xhr.send();
发送POST请求:

const xhr = new XMLHttpRequest();
xhr.open('POST', 'https://jsonplaceholder.typicode.com/users');
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onload = () => {
if (xhr.status === 201) {
console.log(xhr.responseText);
} else {
console.error(Error: ${xhr.status});
}
};
xhr.send(JSON.stringify({
name: 'John Doe',
email: 'johndoe@example.com',
}));

相关文章
|
Web App开发 JavaScript 前端开发
|
Web App开发 JavaScript
【js】判断浏览器是否IE浏览器
搜罗各种方法来判断浏览器是否为IE浏览器 1.最简单的【来自:http://www.cnblogs.com/heganlin/p/5889743.html】 if(!+[1,]){ layer.
1099 0
|
缓存 移动开发 编解码
和我一起来看看浏览器的异步实现到底有哪些方式
前端为何会有异步这一说法,是因为前端的代码是在浏览器中运行的,而浏览器是单线程的,前端的代码是在主线程中运行的,如果有耗时的操作,就会阻塞主线程,导致页面卡顿,所以就有了异步这一说法。
340 0
|
Web App开发 人工智能 JavaScript
浏览器中JavaScript执行原理
原文:浏览器中JavaScript执行原理 本章我们讨论javascript在浏览器中是如果工作的,包括:下载、解析、执行的全过程。javascript的这些讨人嫌的地方我们是知道的: i.需要串行下载 ii.需要解析 iii.需要串行执行 而在chrchromium中,js是这样解析的:(其实第一章末尾已经有了) 至于一些步骤的解释,这里就不再复述了,不懂的请戳:浏览器渲染过程 拉至末尾。
1085 0
|
Web App开发 JavaScript 前端开发