简体   繁体   中英

Filtering JSON to get specific results

I am using the Quotes on Design API https://quotesondesign.com/api-v4-0/ to show random quotes by designers on my site.

However, the idea is to show quotes but only by specific designers randomly .

My code below does not work. Any idea why and how should i go about it to get the desired results.

    $.ajaxSetup(
{  cache: false}
);

function newQuote(){
  $.getJSON('https://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&callback=', function(json,data){
 // Filter to return quotes by Steve Jobs only
    return json.filter(function(data){
      return (data[0].title == "Steve Jobs")
    });
    // add the quote(data[0].content) to my page.
    $('.quote_text').html(data[0].content);
  });

}
// get a new quote everytime i click the button (.message_btn)
$(document).ready(function(){
  newQuote();
  $('.message_btn').on('click',newQuote).fadeIn('slow');
});

Try this code. It appears that the server is using Wordpress legacy API. I've changed the request URL to randomly request for one of the titles in the array.

function newQuote() {
    var titles = ["Steve Jobs", "Jonathan Ive", "Frank Zappa", "Kent Beck"];
    var index = Math.floor(Math.random() * titles.length);
    var url = "https://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[name]=" + titles[index];

    $.getJSON(url, function(data) {

        console.log("data length: " + data.length);
        console.log("returned  title: " + data[0].title);

        if (data.length)
            $('.quote_text').html(data[0].content + " - " + data[0].title);
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM