问题
I am having an issue with the Django TastyPie API and creating a post request in JQuery. The curl request:
curl --dump-header - -H "Content-Type: application/json" -X POST --data '{"created":"1983-01-30 09:20","author":"me","body":"meh", "post":"/api/v1/entry/1/"}' http://localhost:8000/api/v1/comment/
Works totally fine. However, when I try to use the jquery ajax request in the following code. It does absolutely nothing. I have already included XS-Sharing in my settings. I checked in the error console. The JSON for data comes our correctly formatted. It seems to get stuck at OPTIONS with the url provided but I'm not entirely sure. Here's my code:
The api
class EntryResource(ModelResource):
user = fields.ForeignKey(UserResource, 'user')
class Meta:
queryset = Entry.objects.all()
resource_name = 'entry'
authorization = DjangoAuthorization()
filtering = {
'user': ALL_WITH_RELATIONS,
'pub_date': ['exact', 'lt', 'lte', 'gte', 'gt'],
}
class CommentResource(ModelResource):
post = fields.ForeignKey(EntryResource, 'post')
class Meta:
queryset = Comment.objects.all()
resource_name = 'comment'
authorization = Authorization()
MODEL
class Entry(models.Model):
user = models.ForeignKey(User)
pub_date = models.DateTimeField(default=datetime.datetime.now)
title = models.CharField(max_length=200)
slug = models.SlugField()
body = models.TextField()
def __unicode__(self):
return self.title
def save(self, *args, **kwargs):
# For automatic slug generation.
if not self.slug:
self.slug = slugify(self.title)[:50]
return super(Entry, self).save(*args, **kwargs)
class Comment(models.Model):
created = models.DateTimeField(auto_now_add=True)
author = models.CharField(max_length=60)
body = models.TextField()
post = models.ForeignKey(Entry)
def __unicode__(self):
return unicode("%s: %s" % (self.post, self.body[:60]))
class CommentForm(ModelForm):
class Meta:
model = Comment
exclude = ["post"]
HTML
<form id="add_comment" action="{% url blogsite.views.post post.pk%}" method="POST">{% csrf_token %}
<div id="cform">
Name: {{ form.author }}
<p>{{ form.body|linebreaks }}</p>
<input type="hidden" id="post" value= "{{post.pk}}">
</div>
<div id="submit"><input type="submit" value="Submit"></div>
</form>
AND THE JS FILE
$(document).ready(function() {
$('#add_comment').submit(function() {
var data = JSON.stringify({
"created": "1993-01-31 09:18",
"author": $("#id_author").val(),
"body": $("#id_body").val(),
"post": "api/v1/entry/"+ $("#post").val() + "/"
});
console.log(data);
console.log("hello");
$.ajax({
url: 'http://localhost:8000/api/v1/comment/',
type: 'POST',
data: data,
contentType: 'application/json',
processData: false,
success: function(data){
console.log("success");
},
error: function(data){
console.log("There was an error processing" + data);
}
});
});
});
Thanks for any help you can give. I'm running out of ideas as to what could be the problem.
来源:https://stackoverflow.com/questions/13637724/ajax-post-request-to-tastypie-doesnt-do-anything