Ajax:$.get() 从服务器请求数据

通过 HTTP GET 请求从服务器上请求数据。

必需的 URL 参数规定您希望请求的 URL。

可选的 callback 参数是请求成功后所执行的函数名。

   $("button").click(function()
  {$.get("demo_test.php",function(data,status){ alert("数据: 

   " + data + "\ n 状态: " + status); }); }); 
范例:验证用户名是否存在
1、模版 

 

 

 

 

ajax 教程 

 

 

 
 

{%csrf_token%}

视图函数

def gettest(request): 

    return render(request, 'ajaxtest/gettest.html') 

def user_exist(request): 

    uname = request.GET.get('uname') 

     print('register_exist:' + uname) 

    count = 0 

    try: 

         count = UserInfo.objects.filter(nickname=uname).count() 

    except Exception as e: 

         print(e) 

    print('register_exist:'+str(count)) 

    return JsonResponse({'count':count}) 

最后配置url

改造过的:
js代码:
    phone.blur(function(){
            var 
                reg1=/^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/,
                oI=phone.siblings().find('i');
            if(!phone.val()){
                oI.html('手机号不能为空')
                return false;
            }else if(!reg1.test(phone.val())){
                oI.html('手机号不合法')
                return false;
            }else{
                    $.get('/cosme/user_exist/?username=' + phone.val(), function (data) {
                      // alert(data.count)
                      if (data.count == 1) {

                         oI.html('用户名已经存在').show();
                         return false;

                      } else {
                        oI.html('手机号正确')
                         // alert(data.count)
                         return false;

                      }

                });


            }
        })

视图函数:


def user_exist(request):
    # 获取用户名
    username = request.GET["username"]
    print("username :"+username)
    count = 0 # 记录条数0
    try:
        list = User.objects.filter(username=username)
        # print(list)
        count = list.count()
        # get 会报错,filter不会报错
    except Exception as e:
        print(e)
    # print(count)
    return JsonResponse({"count": count})

最后路径配置
前端中使用
注意,js中使用的参数,以及路径问题

你可能感兴趣的:(Ajax:$.get() 从服务器请求数据)