簡體   English   中英

如何從 JavaScript 調用 REST Web 服務 API?

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

我有一個帶有按鈕的 HTML 頁面。 當我點擊那個按鈕時,我需要調用一個 REST Web 服務 API。 我試着在網上到處搜索。 一點頭緒都沒有。 有人可以給我一個線索/先機嗎? 非常感謝。

我很驚訝沒有人提到新的 Fetch API,在撰寫本文時,除 IE11 之外的所有瀏覽器都支持。 它簡化了您在許多其他示例中看到的 XMLHttpRequest 語法。

API 包含更多內容,但從fetch()方法開始。 它需要兩個參數:

  1. 表示請求的 URL 或對象。
  2. 包含方法、標題、正文等的可選 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
}

你的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 年 1 月 11 日更新)

這是另一個使用 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);
        }
      });
});

我認為添加 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();

在我們嘗試在網站前端放置任何東西之前,讓我們打開一個 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>

毫無疑問,最簡單的方法是在 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,我不確定如何修改它。 但這當然很簡單。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM