【发布时间】:2014-10-18 00:39:58
【问题描述】:
我正在尝试在 Django 中使用 jquery 进行发布请求。不幸的是,我还没有成功。确实:我只在萤火虫中看到状态为 200 的发布请求,我得到以下结果(太新,无法发布任何图像):
https://drive.google.com/a/essec.edu/file/d/0B5MagNFQFkbXeVBNV1pfZC1sbk0/view?usp=sharing
谁能帮我找出我做错了什么?
我的代码来自这里: Need a simple working ajax example for django forms ,所以我认为应该是正确的。
仅供参考,在 settings.py 中,我已经评论了 csrf 行以暂时解决该问题:
" #'django.middleware.csrf.CsrfViewMiddleware',"
views.py:
import json
from django.shortcuts import render
from django.http import HttpResponse
def index(request):
return render(request, 'index.html')
def ajax_test(request):
if request.method == 'POST' and request.is_ajax():
name = request.POST['name']
city = request.POST['city']
message = name + ' lives in ' + city
return HttpResponse(json.dumps({'message': message}))
return render(request, 'ajax.html')
index.html:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="/static/js/ajax.js"></script>
<script src="http://getbootstrap.com/dist/js/bootstrap.js"></script>
<form id="my_form" action="" method="post">
<input type="submit" value="Send">
</form>
ajax.js:
$(document).ready(function(){
$("#my_form").submit(function(){
$.post("",
{name:"Donald Duck",
city:"Duckburg",
},
function(data,status){
alert("Data: " + data + "\nStatus: " + status);
})
.fail(function(xhr) {
console.log("Error: " + xhr.statusText);
alert("Error: " + xhr.statusText);
});
return false;
});
});
urls.py:
from django.conf.urls import patterns, url
from polls import views
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^ajax/$', views.ajax_test, name="ajax"),
)
【问题讨论】: