发送Ajax请求的服务器使用jQuery [英] Sending AJAX request to server with jQuery
问题描述
我要发送使用AJAX到相同的URL一个非常基本的post请求。它应该采取用户名和检查对数据库,看是否有该名称的用户已经存在,返回一个字符串的效果。也有一些是错误的JavaScript函数来发送请求:
I want to send a very basic post request using AJAX to the same url. 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:
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")
你有什么可以,为什么JS被忽略看?萤火虫一无所获。
Is there anything you can see as to why the JS is being ignored? Firebug found nothing.
推荐答案
首先,你有你的观点的一些问题。您需要检查POST是否来自AJAX或标准职位;否则,你就无法真正稍后添加用户。 (真的AJAX的部分应该是它自己的观点,因为它确实是不注册过程中本身的一部分,而是一个验证检查。以后,你可能真的想创建通过AJAX的用户,您将无法到,因为该视图将不能在两个不同AJAX请求之间进行区分)。
First, you have some problems in your view. You need to check whether the POST is from AJAX or a standard 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).
其次, GET
不返回无
当对象不存在;它提出了一个 ObjectDoesNotExist
例外。所以,你的如果
语句也将无法正常工作;您必须使用尝试
块来代替。
Next, get
doesn't return None
when the object doesn't exist; it raises an ObjectDoesNotExist
exception. So, your if
statement there won't work; you must use a try
block instead.
我已经更新了下面的观点,因此:
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
这篇关于发送Ajax请求的服务器使用jQuery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!