我的ajax如下:
<script>
$(document).ready(function () {
$.ajaxSetup({
data: {csrfmiddlewaretoken: '{{ csrf_token }}'}
});
$("#submit").submit(function () {
var title = $("#title").val();
var body = $("#body").val();
var images = $("#browsefile")[0].files[0];
$.ajax({
type: "POST",
data: {title: title, body: body, images: images},
url: "{% url 'xxxxx' %}",
success: function (result, statues, xml) {
alert(result);
},
error: function () {
alert("false");
}
})
})
})
</script>
我的网址格式如下:
from django.conf.urls import url
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
from blog import views
urlpatterns = [
url(regex=r'^add/$', view=views.add, name='bbb'),
url(regex=r'^newBlog/$', view=views.addblog, name='xxxxx'),
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
除了ajax将数据发布到addblog方法之外,我得到了POST /add/ HTTP/1.1
。任何人都可以告诉我哪里弄错了,谢谢!
答案 0 :(得分:0)
尝试在提交函数中添加event.preventDefault();
以禁用表单的默认行为,即遵循action属性。
$("#submit").submit(function (event) {
event.preventDefault();
var title = $("#title").val();
var body = $("#body").val();
var images = $("#browsefile")[0].files[0];
formdata = new FormData();
formdata.append("images", images);
formdata.append("body", body);
formdata.append("title", title);
$.ajax({
type: "POST",
data: formdata,
url: "{% url 'xxxxx' %}",
success: function (result, statues, xml) {
alert(result);
},
error: function () {
alert("false");
}
})
return false;
})
修改强>: 每条评论。