我有一个HTML页面上的按钮。当我单击该按钮时,我需要调用一个REST Web服务API。我试着在网上到处找。毫无头绪。有人能给我个提示吗?非常感谢。


当前回答

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

其他回答

毫无疑问,最简单的方法使用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被调用,在当前页面上没有可见的影响。但这当然很简单。

你的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)

我想加上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();

到目前为止,对我来说最简单的是Axios。您可以下载节点模块,也可以将CDN用于更简单的项目。

CDN:

<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

GET/POST的代码示例:

let postData ={key: "some value"}

    axios.get(url).then(response =>{
    //Do stuff with the response.
    })
        
    axios.post(url, postData).then(response=>{
    //Do stuff with the response.
    });

我很惊讶没有人提到新的Fetch API,在写这篇文章的时候,除了IE11,所有的浏览器都支持这个API。它简化了您在许多其他示例中看到的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
}

重新创建前面的顶部答案,一个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
}