通过 Ajax 调取后台接口将返回的 json 数据绑定在页面上 |
您所在的位置:网站首页 › 将ajax将数据显示到页面中 › 通过 Ajax 调取后台接口将返回的 json 数据绑定在页面上 |
第一步:
编写基础的 html 框架内容,并引入 jquery: doctype html> 测试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); }); 合在一起的代码:![]() ![]() --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 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、在页面上显示数据
|
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |