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

Posted

技术标签:

【中文标题】如何从 JavaScript 调用 REST Web 服务 API?【英文标题】:How to call a REST web service API from JavaScript? 【发布时间】:2016-08-26 19:34:25 【问题描述】:

我有一个带有按钮的 html 页面。当我点击那个按钮时,我需要调用一个 REST Web 服务 API。我尝试在网上到处搜索。一点头绪都没有。有人可以在这方面给我一个领导/先机吗?非常感谢。

【问题讨论】:

您对 REST 服务的调用只是对服务器的请求,我想这将是一个 ajax 请求。例如使用 jQuery api.jquery.com/jquery.ajax 【参考方案1】:

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

欲了解更多信息,请访问以下link(2017 年 1 月 11 日更新)

【讨论】:

主线程上的同步 XMLHttpRequest 已被弃用,因为它会对最终用户的体验产生不利影响。如需更多帮助xhr.spec.whatwg.org 由于是同步调用,所以需要调用xhttp.open("POST", "Your Rest URL Here", false);,否则xhttp.responseText不会包含结果。但如前所述,它很快就会被弃用。 如果这是一个 POST 请求,您实际上是在哪里发布数据? "xhttp.setRequestHeader("Content-type", "application/json");" — 这是一个谎言。您没有将任何 JSON 传递给 send() 方法。 当你尝试使用 Service Worker 时,你会后悔使用 XMLHttpRequest 对象而不是使用 fetch()。有一些用于 fetch() 的 polyfill 可在旧版浏览器中使用。学习使用 fetch()。【参考方案2】:
    $("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);
        
      );
);

【讨论】:

【参考方案3】:

这是另一个使用 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>

【讨论】:

您没有遇到任何跨域问题吗?我正在调用从 localhost 托管在其他地方的 api,它给出了跨域问题。 我也面临同样的cors问题..请帮助 @HaritVishwakarma - 如果您调用的 api 没有适用于您的域(本地主机)的 Access-Control-Allow-Origin,则会出现这种情况。尝试创建自己的代理,将 req 发送到代理并将请求转发到您的目的地。由于这将是服务器到服务器的通信,因此不会阻止请求(CORS 被浏览器阻止)。发回此响应,并将 allow-origin 标头设置为 all @HaritVishwakarma 和 NitinWahale 以及未来的开发人员,您可以在本地浏览器上禁用网络安全性,但仅用于测试目的 - 这不能作为生产解决方案。参考这里:***.com/questions/3102819/…【参考方案4】:

我认为添加 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不在同一个域,那不行,对吧?【参考方案5】:

我很惊讶没有人提到新的 Fetch API,除 IE11 之外的所有浏览器都支持在撰写本文时。它简化了您在许多其他示例中看到的 XMLHttpRequest 语法。

API 包含a lot more,但以fetch() 方法开头。它需要两个参数:

    代表请求的 URL 或对象。 包含方法、标头、正文等的可选初始化对象。

简单的 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

重新创建之前的top answer,一个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

【讨论】:

使用此解决方案的按钮操作如何? DELETE 和 PUT 怎么样? @asmaier 您是否得到了有关按钮操作外观的答案?谢谢 button.addEventListener('click', userAction);&lt;button onclick="userAction()" /&gt; 有没有办法在 CosmosDB 中的存储过程或 UDF 中使用类似的 javascript?【参考方案6】:

通常的方法是使用 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>

【讨论】:

【参考方案7】:

在我们尝试在网站前端放置任何东西之前,让我们打开一个 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()

【讨论】:

之前已经给出了类似的答案。你为什么添加你的答案?简短的描述可能会有所帮助【参考方案8】:

毫无疑问,最简单的方法是在 HTML 中使用不可见的 FORM 元素来指定所需的 REST 方法。然后可以使用 JavaScript 将参数插入到input type=hidden 值字段中,并且可以使用一行 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,我不确定如何修改它。但这当然很简单。

【讨论】:

以上是关于如何从 JavaScript 调用 REST Web 服务 API?的主要内容,如果未能解决你的问题,请参考以下文章

从 REST 客户端调用 Worklight Javascript SQL 适配器

如何从服务器端模拟复杂的 REST 调用?

从 Rest 服务接收 excel 文件作为 javascript 响应

使用 jQuery/Ajax 从 JavaScript 调用 WCF/JSON/REST WebService

如何在Javascript中进行rest API调用[重复]

如何使用 javascript/jquery/AJAX 调用 Django REST API?