Почему я не вижу параметры, переданные в адресной строке с помощью запроса Get - PullRequest
0 голосов
/ 18 июня 2019

Я использую javascript / query для отправки содержимого формы с помощью Ajax и запроса Get в PHP. Затем php вернет массив, содержащий кавычки и авторов. Я заметил, что мои параметры не отображаются в адресной строке, хотя я использую запрос GET. И каждый раз, когда используется GET rquest, вы видите что-то вроде «search.php? Q = john + smith». Но мой код не показывает этого ..... Кто-нибудь знает почему? Спасибо

$(document).ready(function() {
  var outputList = document.getElementById("list-output");
  var outputHead = document.getElementById("quote-hd");
  var quoteUrl = "http://localhost/quote/php/quote.php"
  var plcImage = "https://via.placeholder.com/40x40.png";
  var searchData;

  //listener for search button
  $("#search").click(function() {
    outputList.innerHTML = ""; //empty html output
     searchData = $("#search-box").val();
     searchData = searchData.replace(' ', '+'); //for url
     //handling empty search input field
     if(searchData === "" || searchData === null) {
       displayError();
     }
    else {
       // console.log(searchData);
       $.ajax({
          type: 'GET',
          url: 'php/search.php',
          data: 'query='+searchData,
          async: true,
          dataType: "text",
          success: function(res) {
            if (res.totalItems === 0) {
              alert("no result!.. try again")
            }
            else {
              $("#title").animate({'margin-top': '5px'}, 1000); //search box animation
              $(".book-list").css("visibility", "visible");
              displayResults(res);
            }
          },
          error: function () {
            alert("Something went wrong.. <br>"+"Try again!");
          }
        });
      }
      $("#search-box").val(""); //clearn search box
   });

   function displayResults(res) {
      var result = $.parseJSON(res);
      outputHead.style.visibility = "visible";
      for (var i = 0; i < result.length; i++) {        
        var quote = result[i].split('--')[0];
        var author = result[i].split('--')[1];
        // in production code, item.text should have the HTML entities escaped.
        outputList.innerHTML += '<div class="row mt-4">' + formatOutput(quote, author, plcImage) + '</div>';
      }
   }

   function formatOutput(quote, author, plcImage) {
     var htmlCard = `<div class="col-lg-12">
       <div class="card" style="">
         <div class="row no-gutters">
           <div class="col-md-2">
             <img src="${plcImage}" class="card-img">
           </div>
           <div class="col-md-9">
             <div class="card-body">
               <h5 class="card-title quote-cls">${quote}</h5>
               <p class="card-text author-cls">Author: ${author}</p>
             </div>
           </div>
         </div>
       </div>
     </div>`
     return htmlCard;
   }

   function displayError() {
     alert("search term can not be empty!")
   }

});

PHP

<?php
// require 'db/db_connection.php';

if($_GET['query']) {
    $author = $_GET['query'];
    $quotes = '[
        "He who fights with monsters might take care lest he thereby become a monster. And if you gaze for long into an abyss, the abyss gazes also into you. --Nietzsche",     
        "To live is to suffer, to survive is to find some meaning in the suffering. --Nietzsche",   
        "One must still have chaos in oneself to be able to give birth to a dancing star. --Nietzsche",     
        "Reason is not automatic. Those who deny it cannot be conquered by it. Do not count on them. Leave them alone. --Ayn Rand",     
        "Contradictions do not exist. Whenever you think you are facing a contradiction, check your premises. You will find that one of them is wrong. --Ayn Rand"
    ]';
    echo $quotes;
}
?>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...