我遇到了Django TastyPie API的问题,并在JQuery中创建了一个post请求。卷曲请求:
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/
完全正常。但是,当我尝试在以下代码中使用jquery ajax请求时。它什么都没做。我已经在我的设置中包含了XS-Sharing。我检查了错误控制台。我们正确格式化了数据的JSON。它似乎被提供的URL限制在OPTIONS,但我不完全确定。这是我的代码:
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>
和JS文件
$(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);
}
});
});
});
感谢您提供任何帮助。关于可能出现什么问题,我的想法已经不多了。