在JavaScript中调用Web服务接口,可以使用XMLHttpRequest对象或者fetch函数来发送HTTP请求。
使用XMLHttpRequest对象的步骤如下:
-
创建一个XMLHttpRequest对象:
var xmlhttp = new XMLHttpRequest();
-
设置请求方法和URL:
xmlhttp.open("GET", "http://example.com/webservice", true);
-
设置请求头(如果有需要):
xmlhttp.setRequestHeader("Content-Type", "application/json");
-
设置回调函数来处理响应:
xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { var response = JSON.parse(xmlhttp.responseText); // 处理响应数据 } };
-
发送请求:
xmlhttp.send();
使用fetch函数的步骤如下:
-
使用fetch函数发送GET请求:
fetch("http://example.com/webservice").then(response => response.json()).then(data => { // 处理响应数据 }).catch(error => { console.log(error); });
-
使用fetch函数发送POST请求:
fetch("http://example.com/webservice", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(data) }).then(response => response.json()).then(data => { // 处理响应数据 }).catch(error => { console.log(error); });
注意,以上示例假设接口返回的是JSON格式的数据,如果接口返回的是其他格式的数据,则需要相应地进行处理。