Django AJAX请求无法发送 [英] Django AJAX Request Fails To Send
问题描述
我正在尝试创建一个AJAX POST请求来创建一个新的对象。我有一个Tastypie API,我想处理这个请求。
I'm trying to make an AJAX POST request to create a new object. I have a Tastypie API that I would like to handle the request.
这是我的代码。
JS :
<script>
$(document).ready(function (event) {
$('#newpersonalitem').submit(function (event) {
event.preventDefault();
var data = {name: $('#name').val()};
$.ajax({
url: 'http://162.216.18.30:8000/api/v1/personalitem/'
type: 'POST',
contentType: 'application/json',
data: data,
dataType: 'json',
processData: false,
success: function (data) {
location.reload();
console.log(data);
},
});
});
});
</script>
HTML:
<form action="" id='newpersonalitem'>
{% csrf_token %}
New Item: <input type='text' id='name'>
<input type="submit" value="submit">
</form>
当我提交表单重新加载页面,但请求永远不会发送。我已经测试了API,我可以成功地通过移动应用发出同样的请求。非常感谢任何帮助,谢谢。
When I submit the form the pages reloads and but the request is never sent. I have tested the API and I am able to successful make this same request from a mobile app. Any assistance would be greatly appreciated, thanks.
更新:
我以前尝试添加推荐的更改:
UPDATE: I've since tried adding the recommended changes here:
https://docs.djangoproject.com/ en / dev / ref / contrib / csrf /#ajax
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
crossDomain: false, // obviates need for sameOrigin test
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type)) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
我添加了 {%csrf_token%}
在< form>
中。
仍然没有运气。
推荐答案
您可以使用 ajaxForm ,我真的很喜欢它。
You can use ajaxForm, i realy like it.
也许这个工作:
<form action="http://162.216.18.30:8000/api/v1/personalitem/" id='newpersonalitem'>
{% csrf_token %}
New Item: <input type='text' id='name'>
<input type="submit" value="submit">
</form>
<script>
$(document).ready(function (event) {
var options = {
success: function (data) {
console.log(data);
location.reload();
}
};
$('#newpersonalitem').submit(function (event) {
$(this).ajaxSubmit(options);
return false;
});
});
</script>
这篇关于Django AJAX请求无法发送的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!