我正在使用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;
}
?>