原生JS请求接口
get请求
var ajax = new XMLHttpRequest();
ajax.open('get','getStar.php?starName='+name);
ajax.send();
ajax.onreadystatechange = function () {
if (ajax.readyState==4 &&ajax.status==200) {
console.log(ajax.responseText);
}
}
post请求
var xhr = new XMLHttpRequest();
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xhr.open('post', '02.post.php' );
xhr.send('name=fox&age=18');
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
console.log(xhr.responseText);
}
};
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',
async : false,
data:{
page:1,
rows:20,
xmbbm:00000046
},
success:function(data){
console.log(data)
},
error:function () {
alert("服务器内部异常")
}
});
});
})
</script>
</body>
</html>