Django Ajax 发布请求
Posted
技术标签:
【中文标题】Django Ajax 发布请求【英文标题】:Django Ajax Post request 【发布时间】:2020-10-30 13:40:52 【问题描述】:错误是:禁止(CSRF 令牌丢失或不正确。):/tracker/
我尝试了一个 URL:tracker、tracker/、/tracker/、http://127.0.0.1:8000/tracker/'
我是 Django 新手。我尝试了许多 URL,也尝试了 Moesif CORS(Extention)
控制台错误是:jquery-3.5.1.js:10099 POST http://127.0.0.1:8000/tracker/ 403(禁止) 发送@jquery-3.5.1.js:10099 ajax @ jquery-3.5.1.js:9682 (匿名)@(索引):276 调度@ jquery-3.5.1.js:5429 elemData.handle@jquery-3.5.1.js:5233
urls.py 文件:
urlpatterns = [
path('', views.index, name="index"),
path('preview/<int:id>/', views.preview, name="preview"),
path('checkout/', views.checkout, name="checkout"),
path('tracker/', views.tracker, name="tracker"),
]
console.log('工作')
$('#trackerForm').submit(function(event)
$('#items').empty();
var formdata =
'orderId' : $('input[name=order_id]').val(),
'email' : $('input[name=email]').val(),
'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val()
;
$.ajax(
type : 'POST',
url : 'http://127.0.0.1:8000/tracker/',
data:'formdata',
encode: true
)
.done(function(data)
console.log(data)
updates = JSON.parse(data);
if (updates.length > 0 & updates != )
for (i = 0; i < updates.length; i++)
let text = updates[i]['text'];
let time = updates[i]['time'];
mystr = `<li class="list-group-item d-flex justify-content-between align-items-center">
$text
<span class="badge badge-primary badge-pill">$time</span>
</li>`
$('#items').append(mystr);
else
mystr = `<li class="list-group-item d-flex justify-content-between align-items-center">
Sorry, We are not able to fetch this order id and email. Make sure to type correct order Id and email</li>`
$('#items').append(mystr);
)
event.preventDefault();
)
Views.py
def tracker(request):
if request.method == "POST":
order_id = request.POST.get('order_id')
email = request.POST.get('email')
try:
order = Order.objects.filter(order_id=order_id, email=email)
if len(order) > 0:
update = updateOrder.objects.filter(order_id=order_id)
updates = []
for item in update:
updates.append('text':item.order_desc, 'time':item.timestamp)
responce = json.dumps(updates, default=str)
print(responce)
return HttpResponse(responce)
else:
return HttpResponse()
except Exception as e:
return HttpResponse()
context=
return render(request, 'cart/tracker.html', context)
【问题讨论】:
【参考方案1】:去掉'formdata' -> formdata
周围的引号
formdata=
...
...
$.ajax(
type : 'POST',
url : 'http://127.0.0.1:8000/tracker/',
data: formdata,
encode: true
)
【讨论】:
tnx 兄弟我尝试超过 2 小时 @shatishdesai 哈哈,很高兴它有帮助 @shatishdesai 如果解决了您的问题,您也应该接受答案。以上是关于Django Ajax 发布请求的主要内容,如果未能解决你的问题,请参考以下文章
无法将 ajax json 发布请求发送到 django 视图