标签:var status pos port ajax name log request 数据
Ajax
$.ajax({
url: ‘/host‘,
type: "POST",
data: {‘k1‘: 123,‘k2‘: "root"}, //提交的数据
success: function(return_data){
// return_data是服务器端返回的字符串
var obj = JSON.parse(return_data);
}
})
建议:永远让服务器端返回一个字典
return HttpResponse(json.dumps(字典))
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) return HttpResponse(json.dumps(ret)) else: ret[‘status‘] = False ret[‘error‘] = ‘太短了‘ return HttpResponse(json.dumps(ret)) except Exception as e: ret[‘status‘] = False ret[‘error‘] = ‘请求错误‘ return HttpResponse(json.dumps(ret))
<script src="/static/jquery-1.12.4.js"></script> <script> $(function () { $(‘#ajax_submit‘).click(function () { $.ajax({ url:‘/test_ajax‘, type:‘POST‘, data:{‘hostname‘:$(‘#hostname‘).val(),‘ip‘:$(‘#ip‘).val(),‘port‘:$(‘#port‘).val(),‘b_id‘:$(‘#b_id‘).val()}, success:function (return_data) { var obj = JSON.parse(return_data); if (obj.status){ location.reload() }else { alert(obj.error) } } }) }) }) </script>
标签:var status pos port ajax name log request 数据
原文地址:http://www.cnblogs.com/xone/p/6700245.html