jQuery Rest API с необязательными параметрами - PullRequest
0 голосов
/ 30 апреля 2018

Я использую jQuery getJSON для получения сообщений из WP API v2.

У меня есть несколько полей ввода, которые я хочу щелкнуть, а затем добавить дополнительные параметры к URL-адресу запроса.

Пример запроса: Сообщений - https://www.example.com/wp-json/wp/v2/posts? Сообщения из определенной категории - https://www.example.com/wp-json/wp/v2/posts?categories=44

У меня вопрос о том, как мне добавить дополнительные параметры в конец базового URL "https://www.example.com/wp-json/wp/v2/posts?"

Примеры сценариев:

Мне нужно понять, как я могу удалить параметр «категории», если ни один из входов не «проверен». В этом URL также могут быть дополнительные параметры, поэтому есть примеры, когда пользователь может начать добавлять довольно длинный ряд параметров.

Если ни один из входов не выбран, так как он соответствует коду в моем примере, JS fiddle сохраняет параметр "category" в URL, но если ни один из них не выбран в этой категории, он возвращает неверный URL-адрес запроса. Мне нужна помощь в понимании логики для удаления дополнительных параметров, если не выбраны входные данные.

Вот моя JS Fiddle, я комментировал всюду, чтобы помочь объяснить, что я пытаюсь достичь JSFiddle - https://jsfiddle.net/xun2bsyh/4/

Код также:

jQuery(document).ready(function($) {

  $('.search-filter-form .filter-categories input[type="checkbox"]').change(function(e) {
    //example request -  // https://www.sitepoint.com/wp-json/wp/v2/posts?categories=44
    getPosts("categories", this.id);
  });

  // categories parameter and any ID's associated to the category
  var getPosts = function(categories, ids) {

    var html = ""; 
    var postData = "https://www.sitepoint.com/wp-json/wp/v2/posts?" + categories + "=" + ids;

    var request = $.ajax({
      url: postData
    });

    request.done(function(data) {

      // succcessfull response, loop over and render each post returned
      $.each(data, function(index, postData) {

        html += '<li>';
        html += '<article class="article-post">';
        html += '<header><h2><a href="#">' + postData.title.rendered + '</a></h2></header>';
        html += '';
        html += '<a href="' + postData.link + '" class="btn btn-primary">View Now</a>';
        html += '</article>';
        html += '</li>';

      });

        // render items
      $('.listings ul').html(html);

    });

    // handle errors
    request.fail(function(err) {
      console.log(err);
    });

  };

});

<div class="container">
  <div class="job-listing-content">

    <aside class="search-filter">
      <form class="search-filter-form" method="post">
        <div class="search-filter-content">
          <h3 class="title-filter">Search Criteria <i class="fas fa-chevron-down"></i></h3>
          <div class="option-filters-container">
            <div class="option-filter">
              <div class="option-filter-title">
                <h4>Categories Filter</h4>
              </div>
              <ul class="filter-buttons filter-categories">
                <li data-filter="categories">
                  <input type="checkbox" id="44">
                  <label for="44>">Category Node JS</label>
                </li>
                <li data-filter="categories">
                  <input type="checkbox" id="46">
                  <label for="46>">Category Design</label>
                </li>
              </ul>
            </div>
          </div>
        </div>
      </form>
    </aside>

    <div class="listings-container">
      <div class="listing-results">
      </div>
      <div class="listings">
        <ul>

        </ul>
      </div>
    </div>

  </div>
</div>

1 Ответ

0 голосов
/ 30 апреля 2018

Измените прослушиватель событий change ваших флажков на:

var category_checkboxes = $('.search-filter-form .filter-categories input[type="checkbox"]');

category_checkboxes.change(function(e) {
    var categories = [];

    // Get checkboxes that have been checked
    category_checkboxes.each(function(index, element){
        if ( this.checked )
            categories.push( this.id );
    });

    // We have some categories selected, let's display the list
    if ( categories.length )    
        getPosts("categories", categories.join());
    else
        getPosts("", "");
});

... и:

var postData = "https://www.sitepoint.com/wp-json/wp/v2/posts?" + categories + "=" + ids;

до:

var postData = ( categories && ids) ? "https://www.sitepoint.com/wp-json/wp/v2/posts?" + categories + "=" + ids : "https://www.sitepoint.com/wp-json/wp/v2/posts";

Таким образом, если вы не передадите ни таксономию ("категорию"), ни идентификаторы, тогда ваша функция getPosts() вернет все сообщения.

Демо-версия:

jQuery(document).ready(function($) {
  
  var category_checkboxes = $('.search-filter-form .filter-categories input[type="checkbox"]');
  
  category_checkboxes.change(function(e) {
  	var categories = [];
    category_checkboxes.each(function(index, element){
    	if ( this.checked )
    		categories.push( this.id );
    });
    
    // We have some categories selected, let's display the list
    if ( categories.length )    
        getPosts("categories", categories.join());
    else
        getPosts("", "");
  });
	
  // categories parameter and any ID's associated to the category
  var getPosts = function(categories, ids) {

    var html = ""; 
    var postData = ( categories && ids) ? "https://www.sitepoint.com/wp-json/wp/v2/posts?" + categories + "=" + ids : "https://www.sitepoint.com/wp-json/wp/v2/posts";

    var request = $.ajax({
      url: postData
    });

    request.done(function(data) {

      // succcessfull response, loop over and render each post returned
      $.each(data, function(index, postData) {

        html += '<li>';
        html += '<article class="article-post">';
        html += '<header><h2><a href="#">' + postData.title.rendered + '</a></h2></header>';
        html += '';
        html += '<a href="' + postData.link + '" class="btn btn-primary">View Now</a>';
        html += '</article>';
        html += '</li>';

      });
		
    	// render items
      $('.listings ul').html(html);

    });

    // handle errors
    request.fail(function(err) {
      console.log(err);
    });

  };

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="container">
  <div class="job-listing-content">

    <aside class="search-filter">
      <form class="search-filter-form" method="post">
        <div class="search-filter-content">
          <h3 class="title-filter">Search Criteria <i class="fas fa-chevron-down"></i></h3>
          <div class="option-filters-container">
            <div class="option-filter">
              <div class="option-filter-title">
                <h4>Categories Filter</h4>
              </div>
              <ul class="filter-buttons filter-categories">
                <li data-filter="categories">
                  <input type="checkbox" id="44">
                  <label for="44>">Category Node JS</label>
                </li>
                <li data-filter="categories">
                  <input type="checkbox" id="46">
                  <label for="46>">Category Design</label>
                </li>
              </ul>
            </div>
          </div>
        </div>
      </form>
    </aside>

    <div class="listings-container">
      <div class="listing-results">
      </div>
      <div class="listings">
        <ul>

        </ul>
      </div>
    </div>

  </div>
</div>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...