我有一个HTML页面上的按钮。当我单击该按钮时,我需要调用一个REST Web服务API。我试着在网上到处找。毫无头绪。有人能给我个提示吗?非常感谢。
当前回答
我很惊讶没有人提到新的Fetch API,在写这篇文章的时候,除了IE11,所有的浏览器都支持这个API。它简化了您在许多其他示例中看到的XMLHttpRequest语法。
API包含了更多内容,但首先从fetch()方法开始。它有两个参数:
表示请求的URL或对象。 可选的init对象,包含方法,头,主体等。
简单的获得:
const userAction = async () => {
const response = await fetch('http://example.com/movies.json');
const myJson = await response.json(); //extract JSON from the http response
// do something with myJson
}
重新创建前面的顶部答案,一个POST:
const userAction = async () => {
const response = await fetch('http://example.com/movies.json', {
method: 'POST',
body: myBody, // string or object
headers: {
'Content-Type': 'application/json'
}
});
const myJson = await response.json(); //extract JSON from the http response
// do something with myJson
}
其他回答
在我们尝试将任何东西放在网站前端之前,让我们打开一个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()
通常的方法是使用PHP和ajax。但对于你的要求,下面就可以了。
<body>
https://www.google.com/controller/Add/2/2<br>
https://www.google.com/controller/Sub/5/2<br>
https://www.google.com/controller/Multi/3/2<br><br>
<input type="text" id="url" placeholder="RESTful URL" />
<input type="button" id="sub" value="Answer" />
<p>
<div id="display"></div>
</body>
<script type="text/javascript">
document.getElementById('sub').onclick = function(){
var url = document.getElementById('url').value;
var controller = null;
var method = null;
var parm = [];
//validating URLs
function URLValidation(url){
if (url.indexOf("http://") == 0 || url.indexOf("https://") == 0) {
var x = url.split('/');
controller = x[3];
method = x[4];
parm[0] = x[5];
parm[1] = x[6];
}
}
//Calculations
function Add(a,b){
return Number(a)+ Number(b);
}
function Sub(a,b){
return Number(a)/Number(b);
}
function Multi(a,b){
return Number(a)*Number(b);
}
//JSON Response
function ResponseRequest(status,res){
var res = {status: status, response: res};
document.getElementById('display').innerHTML = JSON.stringify(res);
}
//Process
function ProcessRequest(){
if(method=="Add"){
ResponseRequest("200",Add(parm[0],parm[1]));
}else if(method=="Sub"){
ResponseRequest("200",Sub(parm[0],parm[1]));
}else if(method=="Multi"){
ResponseRequest("200",Multi(parm[0],parm[1]));
}else {
ResponseRequest("404","Not Found");
}
}
URLValidation(url);
ProcessRequest();
};
</script>
我很惊讶没有人提到新的Fetch API,在写这篇文章的时候,除了IE11,所有的浏览器都支持这个API。它简化了您在许多其他示例中看到的XMLHttpRequest语法。
API包含了更多内容,但首先从fetch()方法开始。它有两个参数:
表示请求的URL或对象。 可选的init对象,包含方法,头,主体等。
简单的获得:
const userAction = async () => {
const response = await fetch('http://example.com/movies.json');
const myJson = await response.json(); //extract JSON from the http response
// do something with myJson
}
重新创建前面的顶部答案,一个POST:
const userAction = async () => {
const response = await fetch('http://example.com/movies.json', {
method: 'POST',
body: myBody, // string or object
headers: {
'Content-Type': 'application/json'
}
});
const myJson = await response.json(); //extract JSON from the http response
// do something with myJson
}
毫无疑问,最简单的方法使用HTML中不可见的FORM元素指定所需的REST方法。然后,可以使用JavaScript将参数插入到input type=hidden value字段中,并且可以使用一行JavaScript从按钮单击事件侦听器或onclick事件提交表单。下面是一个假设REST API在REST.php文件中的例子:
<body>
<h2>REST-test</h2>
<input type=button onclick="document.getElementById('a').submit();"
value="Do It">
<form id=a action="REST.php" method=post>
<input type=hidden name="arg" value="val">
</form>
</body>
注意,这个示例将用REST.php页面的输出替换页面。 我不知道如何修改这一点,如果你希望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.
});
推荐文章
- 使伸缩项目正确浮动
- Babel 6改变了它导出默认值的方式
- 如何配置历史记录?
- ES6模板文字可以在运行时被替换(或重用)吗?
- [Vue警告]:找不到元素
- 可以在setInterval()内部调用clearInterval()吗?
- AngularJS控制器的生命周期是什么?
- 无法读取未定义的属性“msie”- jQuery工具
- 形式内联内的形式水平在twitter bootstrap?
- 我的蛋蛋怎么不见了?
- JavaScript中的排列?
- 自定义元素在HTML5中有效吗?
- JavaScript中有睡眠/暂停/等待功能吗?
- 如何触发自动填充在谷歌Chrome?
- 创建圈div比使用图像更容易的方法?