下面举一个例子, 使用传统方式,进行Post请求:
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Submittitle>
head>
<body>
<button onclick="apicall()">Make REST API callbutton>
<script >
function apicall() {
var postData = {
"name1": "value1",
"name2": "value2"};
postData = (function(obj){ // 转成post需要的字符串.
var str = "";
for(var prop in obj){
str += prop + "=" + obj[prop] + "&"
}
return str;
})(postData);
var xhr
= new XMLHttpRequest();
var URL=
"localhost:12345/people/1"
xhr.open("POST",URL, true);
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xhr.onreadystatechange = function(){
var XMLHttpReq = xhr;
if (XMLHttpReq.readyState == 4&&XMLHttpReq.status == 200) {
var text = XMLHttpReq.responseText;
console.log(text);
}
};
xhr.send(postData);
}
script>
body>
html>
阅读(1433) | 评论(0) | 转发(0) |