我需要能够存储搜索框术语的文本值,它可以用作 getJson 请求中的查询参数。我将搜索词附加到用户在按 Enter 键后转到的 url 的末尾,但问题是在位置替换时,它显示为错误,因为页面的 url 是/faq/search-results/
.
$(".faq-search").keyup(function(e){
if(e.which == 13) {
window.location.replace("/faq/search-results/" + $(".faq-search").text());
}
});
一旦用户被发送到搜索结果页面,我有一个脚本,如果用户在那个 url 上,应该从 url 中的路径名中获取搜索词,并将其作为查询参数提交给 getJson要求:
if(window.location.pathname == "/faq/search-results/"){
$("document").ready(function(e) {
var url = window.location.pathname;
var exp = url.split(/^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/);
var question = exp[5].split("/")[3];
$.getJSON("//search.url-to-search.com?q=" + question + "&results_type=faq", {
},
//Get results and make 'em look good
function(data) {
console.log(data);
$.each(data.data, function(i, data) {
if(data.type === "FAQ"){
$(".faq-results").append("<li class='result-item'><a href=\"" + data.permalink + "\"><h3>" + data.title + "</h3><p class=\"content\">" + data.text + "</p></a><p class=\"category\">" + data.type + "</p></li>");
}
});
});
});
}
我相信问题在于它不会触发请求,因为它只寻找/faq/search-results/
. 我想我需要一种方法将搜索词存储为变量并将其作为查询参数传递,但不确定如何实现这一点,因为我相信这会使变量超出范围。
您的代码中有几件事是错误的:
首先收集输入值使用 .val() note text()。
其次,您没有将输入值作为查询字符串传递,而是将其添加到 url 路径 /helloWorld。我认为最好添加为查询字符串?q=helloworld。
因此,我调整了您的代码,删除了从路径中提取文本的代码,并实现了一个提取命名查询参数的函数,该函数称为 getParameterByName。
下面的代码应该是不言自明的。
$("document").ready(function(e) {
//
// Collects the input param as passes it as a query string note
// ?q= our string
//
$(".faq-search").keyup(function(e) {
if (e.which == 13) {
window.location.assign("file:///C:/Users/spydre/Desktop/text.html?q=" + $(".faq-search").val());
}
});
// snippet gets a query param from url
function getParameterByName(name, url) {
if (!url) {
url = window.location.href;
}
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
// collect any query string param whos name is q
var question = getParameterByName("q");
if (question) {
// pass question to our getJson
$.getJSON("//search.url-to-search.com?q=" + question + "&results_type=faq", {},
//Get results and make 'em look good
function(data) {
console.log(data);
$.each(data.data, function(i, data) {
if (data.type === "FAQ") {
$(".faq-results").append("<li class='result-item'><a href=\"" + data.permalink + "\"><h3>" + data.title + "</h3><p class=\"content\">" + data.text + "</p></a><p class=\"category\">" + data.type + "</p></li>");
}
});
});
} //if question
})
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句