第一步:
编写基础的 html 框架内容,并引入 jquery:
测试Ajax第二步:
在 “
” 中间插入要点击的按钮和用来显示数据的标签,并编写对应的 function:
“ajax的使用往往配合事件操作进行调用”
点击获取数据
function:
$(function(){
$("#btn").on("click", function(){
//调用 ajax
});
})
第三步:
使用 ajax 调用后台接口并处理数据:
$.ajax({
url: 'http://localhost:53087/test/ajax', //后端程序的url地址
type: 'get',
dataType: 'json',
data:{ //发送给服务器的数据,如果是get请求,也可以写在url地址的?后面
"city":'郑州',
}
})
.done(function(resp){ //请求成功以后的操作(resp是后端返回的json数据,值为:{"city":"郑州"})
console.log(resp);
var data = eval('(' + resp + ')'); //data为json数据转换成的对象,值为:{city: "郑州"}
console.log(data);
var city = data['city'];
console.log(city);
$('#ganmao').html(city)
})
.fail(function(error){ //请求失败以后的操作
console.log(error);
});
合在一起的代码:
测试Ajax$(function(){
$("#btn").on("click", function(){
$.ajax({
//后端程序的url地址
url: 'http://localhost:53087/test/ajax',
type: 'get',
dataType: 'json',
data:{ //发送给服务器的数据,如果是get请求,也可以写在url地址的?后面
"city":'郑州',
}
})
.done(function(resp){ //请求成功以后的操作
console.log(resp);
var data = eval('(' + resp + ')');
console.log(data);
var city = data['city'];
console.log(city);
$('#ganmao').html(city)
})
.fail(function(error){ //请求失败以后的操作
console.log(error);
});
});
})
点击获取数据
View Code
运行效果:
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
PS:
过程中遇到了报错:“Failed to load http://localhost:53087/test/ajax: No 'Access-Control-Allow-Origin’ header is present on the requested resource” 无响应解决方法。百度找到好像是跨域问题,解决方法是 在config里面加上:
//表示允许所有来源进行跨域访问
补充学习:
前端处理 json 数据通常有3步:
1、得到 json 数据
2、解析 json 数据 (可使用 js 中的 eval 函数解析 json 数据,但要为 json 数据加上括号)
3、在页面上显示数据