方式一 使用jquery
$.ajax()是jquery封装的底层使用xmlHttpRequest(ajax)请求远程接口的方法,但要注意,可以通过修改dataType这个属性的值,使用script类型请求远程接口。如果是xml、html、json、text,则请求是xhr类型,如果是script、jsonp,则请求是script类型。
$.ajax({
type:"GET",
url:"http://localhost:9090/getMySeat", //访问的链接
dataType:"json", //数据格式设置为jsonp
jsonp:"callback", //Jquery生成验证参数的名称
success:function(data){ //成功的回调函数
alert(data);
},
error: function (e) {
alert("error");
}
});
$.ajax({
type:"GET",
url:"http://localhost:9090/getMySeat", //访问的链接
dataType:"jsonp", //数据格式设置为jsonp,或者为script
jsonp:"callback", //Jquery生成验证参数的名称
success:function(data){ //成功的回调函数
alert(data);
},
error: function (e) {
alert("error");
}
});
方式二 创建script标签
$(function (){
//页面加载完毕执行,也可以放在点击事件中执行
var script = document.createElement('script');
script.type = 'text/javascript';
// 传参一个回调函数名给后端,方便后端返回时执行这个在前端定义的回调函数
script.src = 'http://localhost:8080/login?user=admin&callback=handleCallback';
document.head.appendChild(script);
})
// 回调执行函数
function handleCallback(res) {
alert(JSON.stringify(res));
}
你的赞和关注是对我最大的肯定,希望大家多多支持,谢谢大家。