我正在尝试使用JSONP设置回调,但我不确定如何在Vue中正确设置它。有人可以提供一点指导吗?
我当前的测试让我收回了数据,因为未定义'。如何才能显示我的帖子标题?
以下是我如何设置它。
JSFIDDLE:https://jsfiddle.net/doss1/z2m1hukL/
我的Vue实例:
var vm = new Vue({
el: '#app',
data: {
thePosts: []
},
created: function(){
$.getScript('https://demo.wp-api.org/?rest_route=/wp/v2/posts&_jsonp=receiveData')
.done(receiveData())
.fail(function(){
console.log('there was an error.');
})
}
});
我的JSONP回调函数在HEAD中链接为<script>
并包含
以下内容:
function receiveData( data ) {
// Do something with the data here.
// For demonstration purposes, we'll simply log it.
console.log( data );
this.thePosts = data;
}
查看/ HTML:
<div id="app" style="margin-top: 5em;">
<article v-for="post in thePosts">
<h2 v-html="post.title.rendered"></h2>
</article>
</div>
答案 0 :(得分:0)
你正在使用jQuery,这使得Vue在很大程度上无关紧要。
使用$.ajax
通过jQuery发出JSONP请求:
$.ajax({
// Use the JSONP data type to stop it using XHR
dataType: "jsonp",
// Pass the URL without the query string
url: 'https://demo.wp-api.org/',
// Use data to provide the query string information
data: {
rest_route: "/wp/v2/posts"
},
// Specify the callback argument NAME with jsonp
jsonp: "_jsonp"
})
// Pass the _function_ you want to handle the response with to `done`. Don't call it immediately and pass the return value
.done(receiveData)
.fail(function(){
console.log('there was an error.');
})
至于recieveData
:
function receiveData( data ) { // Do something with the data here. // For demonstration purposes, we'll simply log it. console.log( data ); this.thePosts = data; }
this
不会保留您想要的值。我不知道你想要什么价值,但你应该使用它。