我是Vue.js的新手。如何将JSON数据从Django视图传递到vue实例(方法)。
Views.py
def articles(request):
model = News.objects.all() # getting News objects list
random_generator = random.randint(1, News.objects.count())
context = {
'title' : 'Articles' ,
'modelSerialize' : serializers.serialize('json',News.objects.all()),
'num_of_objects' : News.objects.count() ,
}
return render(request, 'articles.html',context)
VueScript.js
new Vue({
el: '#list-Of-Articles-Displayed',
data: {
count: 0
},
ready: function() {
this.$http.get('http://127.0.0.1:8000/article/').then(function (response) {
response.status;
console.log(response);
}, function (response) {
alert("error ");
// error callback
});
}
})
Template(article.html)
<div id = "list-Of-Articles-Displayed" class = "col-lg-10" v-for="news in loadArticles" >
<div class = "col-lg-11">
<br>
<a href = "<%news.id%>" ><%news.title%></a>
<h5><small><%news.date%></small></h5>
<p>
<%news.body%>...<span style = "color : purple" > <a href = "<%news.id%>"> Call to Action</a>
<br><br></span>
</p>
</div>
我试图访问VueScript.js中的JSON数据,而不是JSON数据,我得到了完整的HTML结构。
有人能帮我吗。?谢谢
可能是这样的:
视图.py
文章.html
在vue实例中
您可以使用Django Rest Framework将html添加到vue组件中,并通过restful api提供json。要进行API调用,请将vue路由器添加到vue: https://github.com/vuejs/vue-router
或许你应该用
JsonResponse
来代替:您得到的问题是render返回内容类型为
text/html
的响应,而ajax调用需要的是内容类型为application/json
的响应。JsonResponse
是一种快速的方法,可以确保您拥有正确的响应内容类型。您可以阅读更多关于JsonResponsehere的信息,或者阅读此StackOverflowanswer相关问题 更多 >
编程相关推荐