JQuery Rest API с необязательными параметрами

Я использую 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 сохраняет параметр «категории» в URL-адресе, но если ни один из входов не выбран в этой категории, он возвращает неверный URL-адрес запроса. Мне нужна помощь в понимании логики удаления дополнительных параметров, если входы не выбраны.

Вот моя рабочий пример js, я делал комментарии, чтобы помочь объяснить, чего я пытаюсь достичь 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.info(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>
Центр обучения jQuery -> Ajax
Andreas 30.04.2018 12:46
Как конвертировать HTML в PDF с помощью jsPDF
Как конвертировать HTML в PDF с помощью jsPDF
В этой статье мы рассмотрим, как конвертировать HTML в PDF с помощью jsPDF. Здесь мы узнаем, как конвертировать HTML в PDF с помощью javascript.
0
1
309
1
Перейти к ответу Данный вопрос помечен как решенный

Ответы 1

Ответ принят как подходящий

Измените прослушиватель событий 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.info(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>

Отлично. Спасибо за помощь.

Nicholas Rowe 01.05.2018 13:30

Другие вопросы по теме