简体   繁体   English

如何从 JavaScript 调用 REST Web 服务 API?

[英]How to call a REST web service API from JavaScript?

I have an HTML page with a button on it.我有一个带有按钮的 HTML 页面。 When I click on that button, I need to call a REST Web Service API.当我点击那个按钮时,我需要调用一个 REST Web 服务 API。 I tried searching online everywhere.我试着在网上到处搜索。 No clue whatsoever.一点头绪都没有。 Can someone give me a lead/Headstart on this?有人可以给我一个线索/先机吗? Very much appreciated.非常感谢。

I'm surprised nobody has mentioned the new Fetch API, supported by all browsers except IE11 at the time of writing.我很惊讶没有人提到新的 Fetch API,在撰写本文时,除 IE11 之外的所有浏览器都支持。 It simplifies the XMLHttpRequest syntax you see in many of the other examples.它简化了您在许多其他示例中看到的 XMLHttpRequest 语法。

The API includes a lot more , but start with the fetch() method. API 包含更多内容,但从fetch()方法开始。 It takes two arguments:它需要两个参数:

  1. A URL or an object representing the request.表示请求的 URL 或对象。
  2. Optional init object containing the method, headers, body etc.包含方法、标题、正文等的可选 init 对象。

Simple GET:简单的获取:

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
}

Recreating the previous top answer , a POST:重新创建以前的最佳答案,一个 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
}

Your Javascript:你的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");
}

Your Button action::您的按钮操作::

<button type="submit" onclick="UserAction()">Search</button>

For more info go through the following link (Updated 2017/01/11)有关更多信息,请访问以下链接(2017 年 1 月 11 日更新)

Here is another Javascript REST API Call with authentication using json:这是另一个使用 json 进行身份验证的 Javascript REST API 调用:

<script type="text/javascript" language="javascript">

function send()
{
    var urlvariable;

    urlvariable = "text";

    var ItemJSON;

    ItemJSON = '[  {    "Id": 1,    "ProductID": "1",    "Quantity": 1,  },  {    "Id": 1,    "ProductID": "2",    "Quantity": 2,  }]';

    URL = "https://testrestapi.com/additems?var=" + urlvariable;  //Your URL

    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = callbackFunction(xmlhttp);
    xmlhttp.open("POST", URL, false);
    xmlhttp.setRequestHeader("Content-Type", "application/json");
    xmlhttp.setRequestHeader('Authorization', 'Basic ' + window.btoa('apiusername:apiuserpassword')); //in prod, you should encrypt user name and password and provide encrypted keys here instead 
    xmlhttp.onreadystatechange = callbackFunction(xmlhttp);
    xmlhttp.send(ItemJSON);
    alert(xmlhttp.responseText);
    document.getElementById("div").innerHTML = xmlhttp.statusText + ":" + xmlhttp.status + "<BR><textarea rows='100' cols='100'>" + xmlhttp.responseText + "</textarea>";
}

function callbackFunction(xmlhttp) 
{
    //alert(xmlhttp.responseXML);
}
</script>


<html>
<body id='bod'><button type="submit" onclick="javascript:send()">call</button>
<div id='div'>

</div></body>
</html>
    $("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);
        }
      });
});

I think add if (this.readyState == 4 && this.status == 200) to wait is better:我认为添加 if (this.readyState == 4 && this.status == 200) 等待更好:

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
       // Typical action to be performed when the document is ready:
        var response = xhttp.responseText;
        console.log("ok"+response);
    }
};
xhttp.open("GET", "your url", true);

xhttp.send();

Before we try to put anything on the front end of the website, let's open a connection the API.在我们尝试在网站前端放置任何东西之前,让我们打开一个 API 连接。 We'll do so using XMLHttpRequest objects, which is a way to open files and make an HTTP request.我们将使用 XMLHttpRequest 对象来实现,这是一种打开文件和发出 HTTP 请求的方法。

We'll create a request variable and assign a new XMLHttpRequest object to it.我们将创建一个请求变量并为其分配一个新的 XMLHttpRequest 对象。 Then we'll open a new connection with the open() method - in the arguments we'll specify the type of request as GET as well as the URL of the API endpoint.然后我们将使用 open() 方法打开一个新连接 - 在参数中,我们将请求类型指定为 GET 以及 API 端点的 URL。 The request completes and we can access the data inside the onload function.请求完成,我们可以访问 onload 函数中的数据。 When we're done, we'll send the request.完成后,我们将发送请求。
// Create a request variable and assign a new XMLHttpRequest object to it. // 创建一个请求变量并为其分配一个新的 XMLHttpRequest 对象。 var request = new 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()

Usual way is to go with PHP and ajax.通常的方法是使用 PHP 和 ajax。 But for your requirement, below will work fine.但是对于您的要求,下面将正常工作。

<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>

Without a doubt, the simplest method uses an invisible FORM element in HTML specifying the desired REST method.毫无疑问,最简单的方法是在 HTML 中使用一个不可见的 FORM 元素来指定所需的 REST 方法。 Then the arguments can be inserted into input type=hidden value fields using JavaScript and the form can be submitted from the button click event listener or onclick event using one line of JavaScript.然后可以使用 JavaScript 将参数插入到input type=hidden value 字段中,并且可以使用一行 JavaScript 从按钮单击事件侦听器或 onclick 事件提交表单。 Here is an example that assumes the REST API is in file REST.php:这是一个假设 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>

Note that this example will replace the page with the output from page REST.php.请注意,此示例将使用页面 REST.php 的输出替换页面。 I'm not sure how to modify this if you wish the API to be called with no visible effect on the current page.如果您希望在当前页面上没有可见效果的情况下调用 API,我不确定如何修改它。 But it's certainly simple.但这当然很简单。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM