首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Vue2:如何使用JSONP?

Vue2:如何使用JSONP?
EN

Stack Overflow用户
提问于 2017-09-07 13:11:08
回答 1查看 633关注 0票数 0

我正在尝试用JSONP设置回调,但我不知道如何在Vue中正确设置它。有人能提供一点指导吗?

当前的测试将我的数据作为“未定义的”返回。我怎样才能让我的帖子标题出现?

这是我如何设置的。

JSFIDDLE:https://jsfiddle.net/doss1/z2m1hukL/

我的Vue实例:

代码语言:javascript
复制
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>,并包含以下内容:

代码语言:javascript
复制
function receiveData( data ) {
  // Do something with the data here.
  // For demonstration purposes, we'll simply log it.
  console.log( data );
  this.thePosts = data;
}

视图/HTML:

代码语言:javascript
复制
<div id="app" style="margin-top: 5em;">

  <article v-for="post in thePosts">
    <h2 v-html="post.title.rendered"></h2>
  </article>

</div>
EN

回答 1

Stack Overflow用户

发布于 2017-09-07 13:21:57

您使用的是jQuery,这使得Vue在很大程度上无关紧要。

使用$.ajax使用jQuery发出JSONP请求:

代码语言:javascript
复制
$.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将不保存您希望它成为的值。我不知道你想要什么价值,但你应该用它代替。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46097308

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档