原生js调用接口数据和JQuery中Ajax的调用接口
原生js:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>js调接口</title>
</head>
<body>
<button type="button" id="box" "fns()">点击</button>
<script>
//第一步 实例化
var xhr =new XMLHttpRequest();
//第二步,准备发送,请求的方式 地址 是否异步=1
xhr.open("post","http://192.10.78.120:8080/api/zbbbz/query?page=1&rows=20&xmbbm=00000046",
true);
xhr.onreadystatechange = fn;//获到请求的数据之后要做的事情
//第三步,发送请求
function fns() {
xhr.send();
}
//回调函数
function fn() {
if(xhr.readyState==4){
if(xhr.status==200){
//xhr.responseText 请求返回回来的数据
console.log(xhr.responseText)
}
}
}
</script>
</body>
</html>
jquery的ajax:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>ajax调用接口</title>
<script type="text/javascript" src="http://libs.baidu.com/jquery/1.9.1/jquery.js"></script>
</head>
<body>
<button id="btn">提交</button>
<script>
$(function () {
$("#btn").click(function () {
$.ajax({
url:"http://192.10.78.120:8080/api/zbbbz/query",
type:"post", //请求类型
dataType:'json', //返回 JSON 数据
async : false, //是否支持异步刷新,默认是true(异步)
data:{ //需要提交的数据
page:1,
rows:20,
xmbbm:00000046
},
success:function(data){ //请求成功后的回调函数
console.log(data)
},
error:function () { //请求失败后的回调函数
alert("服务器内部异常")
}
});
});
})
</script>
</body>
</html>