Ajax = 异步 JavaScript 和XML。
Ajax是一种用于创建快速动态网页的技术。
HTML
<script>
$(function () {
$("#L_email").blur(function () {
// 1. 获取文本框中的内容
// 2. 发送ajax 请求
var content = $("#L_email").val();
//console.log(content);
//alert(content);
$.ajax({
url: '/seller/type_add_ajax/',
type: 'GET',
data: {'name': content},
success: function (res) {
//alert('成功了');
//console.log(res);
if (res.status == 'true') {
alert('此商品类型已经存在了');
$("#error").text('此商品类型已经存在了')
} else {
$("#error").text('')
}
},
error: function (res) {
alert('error了')
}
})
});
})
</script>
优化后
<script>
$(function () {
$("#btn").click(function () {
// 1. 获取文本框中的内容
var content = $("#L_email").val();
//alert(content);
// 2. 发送ajax 请求
$.ajax({
url: '/seller/type_add1_ajax/',
type: 'POST',
data: {'name': content, 'csrfmiddlewaretoken': "{{ csrf_token }}"},
success: function (res) {
if (res.status == 'true') {
alert('此商品类型已经存在了');
$("#error").text('此商品类型已经存在了')
} else {
$("#error").text('');
//alert('保存成功了...');
var bool = confirm('保存成功,是否继续添加类型?');
if (bool) {
$("#L_email").val(''); // 清空文本框中的内容
} else {
// window.location.href 在当前页面打开url
window.location.href = 'http://127.0.0.1:8999/seller/type_list/';
}
}
},
error: function (res) {
alert('error了')
}
})
});
})
</script>
# ajax 添加类
def type_add_ajax(request):
dic = {'status': 'false'}
if request.method == 'POST':
# 1. 获取ajax 提交过来的内容
type_name = request.POST.get('name')
if type_name:
# 2. 去数据库中查询
ret = models.GoodsType.objects.filter(name=type_name)
if ret:
"""数据库中存在"""
dic['status'] = 'true'
else:
# 3. 返回
"""数据库中不存在"""
models.GoodsType.objects.create(name=type_name)
return JsonResponse(dic)