如何从JavaScript调用RESTWeb服务API?

如何从JavaScript调用RESTWeb服务API?,javascript,html,rest,web-services,Javascript,Html,Rest,Web Services,我有一个带有按钮的HTML页面。当我单击该按钮时,我需要调用RESTWeb服务API。我试着在网上到处搜索。没有任何线索。有人能告诉我这方面的线索吗?非常感谢。您的Javascript: function UserAction() { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.

我有一个带有按钮的HTML页面。当我单击该按钮时,我需要调用RESTWeb服务API。我试着在网上到处搜索。没有任何线索。有人能告诉我这方面的线索吗?非常感谢。

您的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更新)

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

函数send()
{
变量;
urlvariable=“text”;
var-ItemJSON;
ItemJSON='[{“Id”:1,“ProductID”:“1”,“数量”:1,},{“Id”:1,“ProductID”:“2”,“数量”:2,}];
URL=”https://testrestapi.com/additems?var=“+urlvariable;//您的URL
var xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=callbackFunction(xmlhttp);
open(“POST”,URL,false);
setRequestHeader(“内容类型”、“应用程序/json”);
xmlhttp.setRequestHeader('Authorization','Basic'+window.btoa('apiusername:apiuserpassword');//在prod中,您应该加密用户名和密码,并在此处提供加密密钥
xmlhttp.onreadystatechange=callbackFunction(xmlhttp);
send(ItemJSON);
警报(xmlhttp.responseText);
document.getElementById(“div”).innerHTML=xmlhttp.statusText+:“+xmlhttp.status+”
“+xmlhttp.responseText+”; } 函数调用函数(xmlhttp) { //警报(xmlhttp.responseXML); } 呼叫
我认为添加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();

我很惊讶没有人提到新的fetchapi,在撰写本文时,除了IE11之外,所有浏览器都支持它。它简化了您在许多其他示例中看到的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
    }
    
    重新创建上一个帖子:


    通常的方法是使用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>
    
    
    https://www.google.com/controller/Add/2/2
    https://www.google.com/controller/Sub/5/2
    https://www.google.com/controller/Multi/3/2

    document.getElementById('sub')。onclick=function(){ var url=document.getElementById('url')。值; var控制器=null; var方法=null; var parm=[]; //验证URL 函数url验证(url){ if(url.indexOf(“http://”)==0 | | url.indexOf(“https://”)==0){ var x=url.split('/'); 控制器=x[3]; 方法=x[4]; parm[0]=x[5]; parm[1]=x[6]; } } //计算 功能添加(a、b){ 返回编号(a)+返回编号(b); } 职能分包(a、b){ 返回编号(a)/返回编号(b); } 多功能(a、b){ 报税表编号(a)*报税表编号(b); } //JSON响应 功能响应请求(状态,res){ var res={status:status,response:res}; document.getElementById('display').innerHTML=JSON.stringify(res); } //过程 函数ProcessRequest(){ 如果(方法==“添加”){ 响应请求(“200”,添加(parm[0],parm[1]); }否则,如果(方法==“子”){ 响应请求(“200”,Sub(parm[0],parm[1]); }else if(方法==“多”){ 响应请求(“200”,多(parm[0],parm[1]); }否则{ 响应请求(“404”,“未找到”); } } url验证(url); ProcessRequest(); };
    在我们尝试将任何内容放在网站前端之前,让我们打开与API的连接。我们将使用XMLHttpRequest对象来实现这一点,这是一种打开文件并发出HTTP请求的方法

    我们将创建一个请求变量,并为其分配一个新的XMLHttpRequest对象。然后,我们将使用open()方法打开一个新连接——在参数中,我们将指定请求的类型以及API端点的URL。请求完成,我们可以访问onload函数中的数据。完成后,我们将发送请求。
    //创建一个请求变量并为其分配一个新的XMLHttpRequest对象。 var请求=新的XMLHttpRequest()


    毫无疑问,最简单的方法是在HTML中使用一个不可见的表单元素来指定所需的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>
    
    
    休息试验
    
    请注意,此示例将使用page REST.php的输出替换该页面。
    如果希望调用API时不会对当前页面产生任何可见影响,我不确定如何修改此选项。但这当然很简单。

    您对REST服务的调用只是对服务器的一个请求,我想这将是一个ajax请求。例如,主线程上的同步XMLHttpRequest因其对最终用户体验的有害影响而被弃用。要获得更多帮助,因为您正在进行同步调用,您需要调用
    xhttp.open(“POST”,“您的Rest URL在这里”,false),否则xhttp.responseText将不包含结果。但正如前面所说,它很快就会被弃用。如果这是一个POST请求,那么您实际上在哪里发布数据?”
    xhttp.setRequestHeader(“内容类型”,“应用程序/json”);
    ”-这是一个谎言。您没有向
    send()
    方法传递任何JSON。当您尝试使用服务工作者时,您会后悔使用XMLHttpRequest对象而不是使用fetch()。在较旧的浏览器中使用fetch()的多填充。学习使用fetch()。您没有遇到任何跨域问题吗?我正在调用一个从localhost托管在其他地方的api,它会带来跨域问题。我也面临同样的cors问题..plzhelp@HaritVishwakarma-如果您正在调用的api没有访问控制,则将允许您的域(localhost)的源。尝试创建自己的代理,发送请求
    <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>
    
    // 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()
    
    <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>