ajax请求

后端视图函数:

def test_ajax(request):
import json
ret = {"status":True,"error":None,"data":None}
#让请求永远返回一个字典形式
try:
h = request.POST.get('hostname')
i = request.POST.get('ip')
p = request.POST.get('port')
b = request.POST.get('b_id')
if h and len(h) > 5:
models.Host.objects.create(
hostname = h,
ip = i,
port = p,
b_id = b
)
else:
ret['status'] = False
ret['error'] = "too short!!"
except Exception as e:
ret['status'] = False
ret["error"] = 'error!!!'
return HttpResponse(json.dumps(ret))


发送ajax请求:

$("#ajax_submit").click(function(){
$.ajax({
url:"/test_ajax",
{#请求的url #}
type:"POST",
{#请求的方式 #}
data:{'hostname':$("#host").val(),'ip':$("#ip").val(),'port':$("#port").val(),'b_id':$("#sel").val()},
{#请求发送的数据 #}
success:function(d){
{#回调函数,一旦接收到服务端发回来的信息 就 触发该函数 d 是服务端返回的字符串 #}
var obj = JSON.parse(d);
{# 传过来的是类字典的字符串 字符串转换为对象 #}
if(obj.status){
{# obj.status 是状态 #}
location.reload();
{# 刷新页面 #}
}else{
$("#err_msg").text(obj.error);
{# 打印错误信息 obj.error 是错误信息 #}
}
}
})
})
原文地址:https://www.cnblogs.com/fanxuanhui-linux/p/6218677.html