Javascript 为什么ajax调用没有';t give.u ajax()是真的吗?
My template.html:Javascript 为什么ajax调用没有';t give.u ajax()是真的吗?,javascript,ajax,django,django-views,Javascript,Ajax,Django,Django Views,My template.html: ... <button class="btn btn-success" onclick="save_post(event, 'publish')">Publish</button> ... My views.py: @staff_member_required def post_new(request): context_dict=[] if request.method == "POST": if r
...
<button class="btn btn-success" onclick="save_post(event, 'publish')">Publish</button>
...
My views.py:
@staff_member_required
def post_new(request):
context_dict=[]
if request.method == "POST":
if request.is_ajax():
#code
...
else:
form = PostForm()
return render(request, 'blog/post_edit.html', context_dict)
我的url.py
:
app_name = 'blog'
urlpatterns = [
...
path('post/new/', views.post_new, name='post_new'),
path('post/<int:pk>/edit/', views.post_edit, name='post_edit'),
...
ajax不调用视图。编辑:我解决了这个问题,但我明天继续:)您的Ajax代码有一些问题,视图是正确的 我已附上我的代码附加图像和代码
$.ajax({
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
url : 'myajaxview', // the url where we want to POST
data :{
'csrfmiddlewaretoken': '{{csrf_token}}',
'text': text,
'search': search,
'email': email,
'url': url,
'telephone': telephone,
'password': password,
'number': number,
},
dataType : 'json', // what type of data do we expect back from the server
encode : true
})
如果您不使用
preventDefault
,则在回调完成后,浏览器仍将提交表单(默认操作)。我的猜测是,request.is\u ajax()
在save\u post event.preventDefault()中返回False
;给出错误:未定义事件。我试图保存帖子(事件,发布),但没有成功,因为你没有通过该事件OK,我通过了该事件,但现在它说:找不到:/blog/post\u new/并且没有调用视图…如果你没有显示你的url模式,我们如何帮助找不到错误?你对这个回答有什么问题我没有投反对票,但是如果你能解释一下什么是错的,什么是你修正的,答案会更好。包括代码就足够了,你不需要截图。不是我的否决票,但我不能让你的代码为我工作。但我仍在研究它。您需要在数据和方法数据类型中添加form csrf令牌,encode missed出于这个原因,我添加了Code以供更多参考我的github项目
Not Found: /blog/post_new/
[26/Jan/2018 19:07:20] "POST /blog/post_new/ HTTP/1.1" 404 10871
$.ajax({
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
url : 'myajaxview', // the url where we want to POST
data :{
'csrfmiddlewaretoken': '{{csrf_token}}',
'text': text,
'search': search,
'email': email,
'url': url,
'telephone': telephone,
'password': password,
'number': number,
},
dataType : 'json', // what type of data do we expect back from the server
encode : true
})