我有一个HTML页面上的按钮。当我单击该按钮时,我需要调用一个REST Web服务API。我试着在网上到处找。毫无头绪。有人能给我个提示吗?非常感谢。
当前回答
到目前为止,对我来说最简单的是Axios。您可以下载节点模块,也可以将CDN用于更简单的项目。
CDN:
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
GET/POST的代码示例:
let postData ={key: "some value"}
axios.get(url).then(response =>{
//Do stuff with the response.
})
axios.post(url, postData).then(response=>{
//Do stuff with the response.
});
其他回答
在我们尝试将任何东西放在网站前端之前,让我们打开一个API连接。我们将使用XMLHttpRequest对象,这是一种打开文件并发出HTTP请求的方法。
我们将创建一个请求变量,并将一个新的XMLHttpRequest对象分配给它。然后,我们将使用open()方法打开一个新连接——在参数中,我们将指定请求的类型为GET以及API端点的URL。请求完成后,我们可以访问onload函数中的数据。完成后,我们会发送请求。 //创建一个请求变量,并分配一个新的XMLHttpRequest对象给它。 var request = new XMLHttpRequest()
// Open a new connection, using the GET request on the URL endpoint
request.open('GET', 'https://ghibliapi.herokuapp.com/films', true)
request.onload = function () {
// Begin accessing JSON data here
}
}
// Send request
request.send()
到目前为止,对我来说最简单的是Axios。您可以下载节点模块,也可以将CDN用于更简单的项目。
CDN:
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
GET/POST的代码示例:
let postData ={key: "some value"}
axios.get(url).then(response =>{
//Do stuff with the response.
})
axios.post(url, postData).then(response=>{
//Do stuff with the response.
});
$("button").on("click",function(){
//console.log("hii");
$.ajax({
headers:{
"key":"your key",
"Accept":"application/json",//depends on your api
"Content-type":"application/x-www-form-urlencoded"//depends on your api
}, url:"url you need",
success:function(response){
var r=JSON.parse(response);
$("#main").html(r.base);
}
});
});
如果这对任何人都有帮助,如果你对外部库没问题,那么我可以为Axios担保,它有一个非常干净的API和丰富的文档来处理REST调用,下面是一个例子
const axios = require('axios');
axios.get('/user?ID=12345')
.then(function (response) {
// handle success
console.log(response);
});
你的Javascript:
function UserAction() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
alert(this.responseText);
}
};
xhttp.open("POST", "Your Rest URL Here", true);
xhttp.setRequestHeader("Content-type", "application/json");
xhttp.send("Your JSON Data Here");
}
你的按钮动作::
<button type="submit" onclick="UserAction()">Search</button>
欲了解更多信息,请通过以下链接(更新2017/01/11)
推荐文章
- 使用lodash将对象转换为数组
- 打印在 JsFiddle 中
- AngularJS只适用于单页应用程序吗?
- Javascript和regex:分割字符串并保留分隔符
- 如何检查DST(日光节约时间)是否有效,如果是,偏移量?
- 如何打破_。在underscore.js中的每个函数
- 在HTML中还有其他有用的空格码吗,比如半空格的 , em-spaces, en-spaces等等?
- 如何在jQuery中获得当前日期?
- 如何创建一个日期对象从字符串在javascript
- 输入触发器按钮单击
- 获取对象的属性名
- 如何检查用户是否可以回到浏览器历史
- OData和REST web服务的区别
- 相当于字符串。jQuery格式
- 如何在vue-cli项目中更改端口号