jQuery对ajax的终极支持!!!
# 最高频使用的8个参数: 参数对象中的属性: 1.url:字符串,表示异步请求的地址 2.type:字符串,请求方式:get或post 3.data:传递到服务器端的参数 1、字符串:"name=geng&age=18" 2、js对象: { name:‘geng‘, age:18 csrf: } 4.dataType:字符串,响应回来的数据的格式 1.‘html‘ 2.‘xml‘ 3.‘text‘ 4.‘script‘ 5.‘json‘ 6.‘jsonp‘ //有关跨域的响应格式 5.success:回调函数,请求和响应成功时,回来执行的操作 6.error:回调函数,请求或响应失败时,回来执行的操作 7.beforeSend:回调函数,发送ajax请求之前,执行的操作,如:return false,则终止请求 8.async:是否为异步请求,true为异步,false为同步
$.ajax({ url:‘‘, type:‘get‘/‘post‘, data:{ name:‘‘, csrfmiddlewaretoken:$("[name=‘csrfmiddlewaretoken‘]").val(), }, dataType:‘json‘, success:function () { }, error:function(){ }, beforeSend:function(){ }, })
$("button").click(function(){
$.ajax({
url:"demo_test.txt",
type:‘post‘,
data:{
name:‘‘,
csrfmiddlewaretoken:$("[name=‘csrfmiddlewaretoken‘]").val(),
},
dataType:‘json‘,
success:function(result){
$("#div1").html(result);
},
beforeSend:function(){
},
});
});
场景:用户注册
功能:
用户输入账号密码完毕
点击【提交】按钮完毕
在网络传输过程中,网速慢的情况下,显示动画效果,等待服务器响应
在网络传输过程中,网速慢的情况下,提交按钮变为灰色不可用状态,直到得到服务器响应
代码实现:
<head>
// 引入jQuery
<script type="text/javascript" src="{% static ‘bootstrap-3.3.7/js/jquery-1.12.4.min.js‘ %}"></script>
</head>
?
{# $.ajax() #}
<body>
<span id="loading" style="display: none">加载中...[我是动画]</span>
<button id="btn">jquery ajax</button>
?
<script>
$(function () {
$(‘#btn‘).click(function () {
$.ajax({
url: ‘/ajax/jquery_ajax‘,
type: ‘post‘,
data:{
csrfmiddlewaretoken: $("[name=‘csrfmiddlewaretoken‘]").val(),
?
},
dataType:‘json‘,
async:true,
?
success:function () {
// post 请求发送成功
$(‘#loading‘).hide(3000); // 3秒内消失
// 弹框:登录成功
alert(‘登录成功‘);
?
// 提交按钮改为可用状态
$(‘#btn‘).removeAttr(‘disabled‘);
?
},
?
error:function () {
?
},
?
beforeSend:function () {
// 发送前,do something
$(‘#loading‘).show(); // 发送前,让等待元素span显示(show)
?
// 发送前,让button置灰,不可点击
$(‘#btn‘).attr({disabled:‘disabled‘})
?
},
})
})
})
</script>
</body>
场景:异步刷新用户列表界面
实例:
<head>
// 引入jQuery
<script type="text/javascript" src="{% static ‘bootstrap-3.3.7/js/jquery-1.12.4.min.js‘ %}"></script>
</head>
?
<body>
<button id="btn">show data</button>
<thead>
<tr>
<th>name</th>
<th>age</th>
</tr>
</thead>
<tbody id="show"></tbody>
?
<script>
$(function () {
$(‘#btn‘).click(function () {
$.ajax({
url: ‘/ajax/jquery_show‘,
type: ‘get‘,
dataType: ‘json‘,
async: true,
data: {},
success: function (data) {
var html = ‘‘;
?
$.each(data, function (i, obj) {
html += ‘<tr>‘;
html += ‘<td>‘ + obj.name + ‘</td>‘;
html += ‘<td>‘ + obj.age + ‘</td>‘;
html += ‘</tr>‘;
});
$(‘#show‘).html(html); // 在id= show的html标签显示用户信息
},
?
error: function () {
?
},
?
beforeSend: function () {
?
},
})
})
})
</script>
</body>
原文:https://www.cnblogs.com/gengyufei/p/12589175.html