简体   繁体   English

使用jQuery发送AJAX请求到服务器

[英]Sending AJAX request to server with jQuery

I want to send a very basic post request using AJAX to the same url. 我想使用AJAX向相同的网址发送一个非常基本的帖子请求。 It should take the username and check it against the DB to see if a user with that name exists already, returning a string to that effect. 它应该使用用户名,并对照数据库进行检查,以查看是否已经存在具有该名称的用户,并返回一个字符串。 There is something wrong with the javascript function that is sending the request: 发送请求的javascript函数有问题:

function usernameCheck(){
$.post("http://omnicloud.me/signup", 
  {username: $("#username").value}, 
  function(response){
    if(response=="true"){
       $('#passAlert').innerHTML("Sorry, that username is already taken")
    }
});

return !($('#passAlert').value == "Sorry, that username is already taken")
}

If the person is just loading the signup view, it returns the page, otherwise, it is being called to check for a user existing: 如果此人只是在加载注册视图,则它将返回页面,否则,将调用该页面以检查现有用户:

def signup(request):
    if request.method == 'GET':
        return render_to_response('signup.html', context_instance=RequestContext(request))
    else: 
    #query db for user with username provided in POST, return if it exists
        user = User.objects.get(username=request.POST["username"]) 
        if user is not None:
            return HttpResponse("true")
        else:
            return HttpResponse("false")

Is there anything you can see as to why the JS is being ignored? 关于JS为什么被忽略,您能看到什么吗? Firebug found nothing. 萤火虫一无所获。

Ajax means "Asynchronous JavaScript and XML" so it does not wait for $.post to finish but just goes on within your code. Ajax的意思是“异步JavaScript和XML”,因此它不等待$ .post完成,而只是在您的代码中进行。

To solve this issue you have to use a callback function: 要解决此问题,您必须使用回调函数:

http://api.jquery.com/jQuery.post/ http://api.jquery.com/jQuery.post/

jQuery.post( url [, data] [, success(data, textStatus, jqXHR)] [, dataType] ) jQuery.post(url [,data] [,success(data,textStatus,jqXHR)] [,dataType])

url A string containing the URL to which the request is sent. url包含请求发送到的URL的字符串。

data A map or string that is sent to the server with the request. 数据与请求一起发送到服务器的映射或字符串。

success(data, textStatus, jqXHR) A callback function that is executed if the request succeeds. success(data,textStatus,jqXHR)如果请求成功,则执行一个回调函数。

dataType The type of data expected from the server. dataType服务器期望的数据类型。 Default: Intelligent Guess (xml, json, script, or html). 默认值:Intelligent Guess(xml,json,脚本或html)。

Sample: 样品:

function usernameCheck(){
    $.post("http://omnicloud.me/signup", 
      {username: $("#username").val()}, 
      function(response){
        if(response=="true"){
           $('#passAlert').html("Sorry, that username is already taken")
        }
    });
}

You might also pass an anonymous callback: 您可能还会传递匿名回调:

function usernameCheck(successCallback){
    $.post("http://omnicloud.me/signup", 
      {username: $("#username").val()}, 
      function(response){
       if(response=="true") successCallback();
    });
}

// Somewhere else in your code:

usernameCheck(function(){
  $('#passAlert').html("Sorry, that username is already taken")
});

First, you have some problems in your view. 首先,您认为有一些问题。 You need to check whether the POST is from AJAX or a standard POST; 您需要检查POST是来自AJAX还是来自标准POST。 otherwise, you won't be able to actually add the user later. 否则,您以后将无法实际添加用户。 (Really the AJAX part should be it's own view, since it really isn't part of the signup process per se, but rather a validation check. Later, you might actually want create a user via AJAX, and you wouldn't be able to because the view wouldn't be able to distinguish between the two different AJAX requests). (实际上,AJAX部分应该是它自己的视图,因为它实际上本身并不是注册过程的一部分,而是验证检查。稍后,您可能实际上想通过AJAX创建用户,而您将无法因为视图将无法区分两个不同的AJAX请求)。

Next, get doesn't return None when the object doesn't exist; 接下来,当对象不存在时, get不会返回None it raises an ObjectDoesNotExist exception. 它引发一个ObjectDoesNotExist异常。 So, your if statement there won't work; 因此,您的if语句将不起作用; you must use a try block instead. 您必须改用try块。

I've updated your view below, accordingly: 因此,我在下面更新了您的视图:

def signup(request):
    if request.method == 'GET':
        return render_to_response('signup.html', context_instance=RequestContext(request))
    elif request.is_ajax(): 
        # query db for user with username provided in POST, return if it exists
        try:
            user = User.objects.get(username=request.POST["username"]) 
        except User.DoesNotExist:
            return HttpResponse("false")
        else:
            return HttpResponse("true")
    else:
        # Normal post, add new user

EDIT: make sure the response sends back a STRING true or a STRING false 编辑:确保响应返回STRING真或STRING假

EDIT: the response IS SENDING BACK A STRING true or A STRING false 编辑:响应发送回STRING真或STRING假

function usernameCheck(){
    var exists;
    $.post("http://omnicloud.me/signup", { username: $("#username").val() }, 
      function(response){
         exists = (response == 'true');
         if(exists){
             $('#passAlert').innHTML = "Sorry, that username is already taken";
             return false;
         } else {
             return true;
         }
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM