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

Sha*_*Ali 124 html javascript rest web-services

我有一个HTML页面,上面有一个按钮.当我点击该按钮时,我需要调用Rest Web Service API?我试着到处搜索.毫无头绪.有人可以给我一个领导/ Headstart吗?非常感谢

Bre*_*ill 105

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

API包含更多内容,但从fetch()方法开始.它需要两个参数:

  1. 表示请求的URL或对象.
  2. 包含方法,标题,正文等的可选init对象

简单的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
}
Run Code Online (Sandbox Code Playgroud)

重新创建上一个回答,一个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
}
Run Code Online (Sandbox Code Playgroud)

  • 删除和放置怎么样? (7认同)
  • 此解决方案的按钮操作是什么样的? (3认同)
  • `button.addEventListener('click', userAction);` 或 `<button onclick="userAction()" />` (3认同)
  • @asmaier 你得到关于按钮操作是什么样子的答案吗?谢谢 (2认同)

Abh*_*hek 102

你的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");
}
Run Code Online (Sandbox Code Playgroud)

你的按钮动作::

<button type="submit" onclick="UserAction()">Search</button>
Run Code Online (Sandbox Code Playgroud)

欲了解更多信息,请浏览以下链接(更新时间:2017年2月)

  • 主线程上的同步XMLHttpRequest因其对最终用户体验的不利影响而被弃用.如需更多帮助http://xhr.spec.whatwg.org/ (18认同)

小智 17

这是另一个使用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>
Run Code Online (Sandbox Code Playgroud)


aay*_*shi 11

    $("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);
        }
      });
});
Run Code Online (Sandbox Code Playgroud)


mar*_*985 7

我认为添加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();
Run Code Online (Sandbox Code Playgroud)