问题
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.
Here is my code.
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>
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);
}
}
});
and I added {% csrf_token %}
in the <form>
.
Still with no luck.
回答1:
You can use ajaxForm, i realy like it.
Maybe this works:
<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>
来源:https://stackoverflow.com/questions/20477222/django-ajax-request-fails-to-send