我正在努力为django创建一个shoutbox。现在一切正常,从数据库中读取数据,但是当我想添加一个新的呼叫时,整个页面正在重新加载,并且从我能够检查 - 表单的动作保持不变,并且没有请求发送到函数在指定的网址下。我在这里做错了什么?
HTML:
<div id="shoutbox">
<form method="post" id="form" class="shoutbox-form">
<table>
<tr>
<td><label>User</label></td>
<td><input class="text user" id="nick" type="text" MAXLENGTH="25" /></td>
</tr>
<tr>
<td><label>Message</label></td>
<td><input class="text" id="shout" type="text" MAXLENGTH="255" /></td>
</tr>
<tr>
<td></td>
<td><input id="send-shout" type="submit" value="Dodaj!" /></td>
</tr>
</table>
</form>
<div id="shoutbox-container">
<span class="clear"></span>
<div class="shoutbox">
<div id="shoutbox-loading"><img src="css/images/loading.gif" alt="Loading..." /></div>
<ul>
</ul>
</div>
</div>
</div>
jQuery:
$(document).ready(function(){
var inputUser = $("#nick");
var inputMessage = $("#shout");
var loading = $("#shoutbox-loading");
var messageList = $(".shoutbox > ul");
function updateShoutbox(){
messageList.hide();
loading.fadeIn();
$.ajax({
type: "POST",
url: "/shouts/",
data: "action=refresh",
dataType: "json",
success: function(data){
loading.fadeOut();
var c = data["response"];
messageList.html(c);
messageList.fadeIn(2000);
}
});
}
function checkForm(){
if(inputUser.attr("value") && inputMessage.attr("value"))
return true;
else
return false;
}
updateShoutbox();
$("#shoutbox-form").submit(function(){
if(checkForm()){
var nick = inputUser.attr("value");
var message = inputMessage.attr("value");
$("#send-shout").attr({ disabled:true, value:"Sending..." });
$("#send-shout").blur();
$.ajax({
type: "POST",
async: true,
url: "/shouts/",
data: "action=insert&user=" + nick + "&message=" + message,
//data: {"action" : "insert", "user": user, "message": message},
dataType: "json",
complete: function(data){
var c = data["response"];
messageList.html(c);
updateShoutbox();
$("#send-shout").attr({ disabled:false, value:"Shout!" });
}
});
}
else alert("All fields needed!");
return false;
});
});
我的网址:
url(r'^shouts/?$', "shoutbox"),
功能:
def shoutbox(request, user=None, message=None):
response = ""
if not request.POST.get("action"):
return HttpResponseRedirect('/')
else:
req = request.POST.get("action")
if req == "insert":
response = shoutbox_add(message, user)
elif req == "refresh":
response = shoutbox_get(20)
if request.is_ajax():
result = simplejson.dumps({
'response': response
}, cls=LazyEncoder)
return HttpResponse(result, mimetype='application/javascript')
答案 0 :(得分:1)
你的表单有id'表单'和类'shoutbox-form',所以你的选择器应该是
$("#form").submit(function(){
或
$(".shoutbox-form").submit(function(){