gpt4 book ai didi

javascript - shift() 和 pop() 不是函数

转载 作者:行者123 更新时间:2023-11-29 18:58:18 25 4
gpt4 key购买 nike

所以我出于学习目的制作了一个随机报价生成器机器项目,但遇到了错误。我尝试在其他答案中寻找它,但无法理解/解决它。这是 JS 代码:

    $('#new').on('click', function(e) {
e.preventDefault();
$.ajax( {
url: 'https://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&_jsonp=mycallback',
success: function(data) {
console.log(data);
var post = data.shift(); // The data is an array of posts. Grabbing the first one.
$('.author').text(post.title);
console.log(post.title);
$('.quote').html(post.content);
console.log(post.content);
},
cache: false
});
});

对于第一个 console.log,它以数组形式显示数据,所以我尝试了 pop 和 shift 函数来提取数据。这是数据格式:

/**/mycallback([{"ID":1640,"title":"Scott Belsky","content":"<p>To envision what will be, you must remove yourself from the constant concern for what already is.<\/p>\n","link":"https:\/\/quotesondesign.com\/scott-belsky\/","custom_meta":{"Source":"<a href=\"http:\/\/the99percent.com\/book\">book<\/a>"}}])

它为接下来的 2 个 console.log() 给出了 undefined 。这是错误:

Uncaught TypeError: data.shift is not a function

它在两个函数上都给出了错误。任何帮助将不胜感激。

最佳答案

两件事:

  • 不要定义回调函数。通过将显式函数名称替换为 ?
  • 将其留给 $.ajax
  • 设置数据类型为jsonp

$.ajax( {
url: 'https://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&_jsonp=?',
dataType:'jsonp',
cache: false,
success: function(data) {
console.log(data);
var post = data.shift();
console.log(post);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>

关于javascript - shift() 和 pop() 不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48137329/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com