简体   繁体   中英

How to send filters to an api with javascript

I have a catalog list with a 'favorite' option. Now I'm trying to make a watchlist that only shows the selected favorites. The data comes from the same api, but now for the watchlist I need to filter the api data to only show the favorites.

This is the code

    "watchlist": {
  cols: 5,
  promise: function() {
    return $.api("/catalog", {
      count: 4,
    }).then(
      function(result) {
        $(".dashboardpage .widget-watchlist").render('pages/dashboard/widget-watchlist', {
          watchlist: result.data
        }).animo("enterContent");
      },
      function(err) {
        $(".dashboardpage .widget-watchlist").render('pages/dashboard/widget-watchlist', {
          watchlist: [],
          error: err
        }).animo("enterContent");
      }
    );
  }
},

This is the JSON data

data: [{score: 4, id: 49878, description: "ACT 230V aansluitkabel C13 - C14 blauw. Lengte: 3 m",…},…]
filters: {price: ["0", "9999999999"], in_stock: "0", category: "", price_limit: [1, 8], search: "",…}
category: ""
favorite: {doc_count: 15, filtered: {doc_count_error_upper_bound: 0, sum_other_doc_count: 0, buckets: []}}
doc_count: 15

This is entirely based off of the API that you are communicating with. The api would have provide hooks to filter based on what you want. This could be done using query parameters `ie $.api("/catalog?type=favorites". But this is an impossible question to completely answer without that information.

Filter result.data and give only filtered items to watchlist when promise gets resolved.

function(result) {
    $(".dashboardpage .widget-watchlist").render('pages/dashboard/widget-watchlist', {
      watchlist: result.data.filter(item => favoriteItemIds.indexOf(item.id) != -1)
    }).animo("enterContent");
}

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