我正在尝试用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回调函数在头中被链接为一个<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>发布于 2017-09-07 13:21:57
您使用的是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
函数receiveData(数据){ //处理这里的数据。//为了演示目的,我们将简单地记录它。console.log(数据);this.thePosts = data;}
this将不保存您希望它成为的值。我不知道你想要什么价值,但你应该用它代替。
https://stackoverflow.com/questions/46097308
复制相似问题