JS怎么调用API接口,谢谢?

您所在的位置:网站首页 javascript网络 JS怎么调用API接口,谢谢?

JS怎么调用API接口,谢谢?

2023-03-07 16:53| 来源: 网络整理| 查看: 265

浏览器端 JS 调用 API 大概有三种方式,XHR、jQuery、Fetch。

下面分别给出例子。具体细节请参阅 《AJAX 之 XHR, jQuery, Fetch 的对比》

1. XMLHttpRequest

// POST var xhr; if (window.XMLHttpRequest) { // Mozilla, Safari... xhr = new XMLHttpRequest(); } else if (window.ActiveXObject) { // IE try { xhr = new ActiveXObject('Msxml2.XMLHTTP'); } catch (e) { try { xhr = new ActiveXObject('Microsoft.XMLHTTP'); } catch (e) {} } } if (xhr) { xhr.onreadystatechange = onReadyStateChange; xhr.open('POST', '/api', true); // 设置 Content-Type 为 application/x-www-form-urlencoded // 以表单的形式传递数据 xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xhr.send('username=admin&password=root'); } // onreadystatechange 方法 function onReadyStateChange() { // 该函数会被调用四次 console.log(xhr.readyState); if (xhr.readyState === 4) { // everything is good, the response is received if (xhr.status === 200) { console.log(xhr.responseText); } else { console.log('There was a problem with the request.'); } } else { // still not ready console.log('still not ready...'); } }

2. jQuery

$.ajax({ method: 'POST', url: '/api', data: { username: 'admin', password: 'root' } }) .done(function(msg) { alert( 'Data Saved: ' + msg ); });

3. fetch

var options = { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, body: JSON.stringify({ username: 'admin', password: 'root' }), credentials: 'include' }; fetch('/api', options).then(response => response.json()) .then(data => console.log(data)) .catch(error => console.log('Oops, error: ', error))

---

提交总是出错,我也很无奈 T_T 405 Method Not Allowed



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3