javascript - Javascript - 从输入提交加载 URL 而没有“return: false;”
问题描述
我有这个在提交时执行 blogSearch() 的表单:
<form onsubmit="return blogSearch();">
<input class="mb0" type="text" id="blogsearchinput" placeholder="Search..." />
</form>
这是我的javascript:
function blogSearch() {
var test = document.getElementById("blogsearchinput").value
window.location.href = "../list.php";
return false;
}
我想在页面加载后在函数 blogSearch() 中运行更多的 javascript,但显然在返回 false 后我不能这样做。只有当我返回 false 时页面才会加载,因为我读到这将覆盖默认输入提交。
有没有一种方法可以从输入提交加载 URL 而无需返回 false?或者以某种方式我可以在加载后继续运行功能?
解决方案
您不能使用 显示在同一页面上的搜索结果window.location
,这会将您带到另一个页面。在这种情况下,您可能希望使用
XHR 请求来获取数据,然后将其显示在同一页面上。
我对 HTML 做了一些修改:
<form id="search-form">
<label>Search blog: <input class="mb0" type="search" id="search-query"></label><input type="submit" value="Search">
</form>
<ul id="search-results"></ul>
然后在 list.php 你会做这样的事情:
<?php
// get the q parameter that we will be setting in our XHR request
$query = isset($_GET['q']) ? $_GET['q'] : '';
// I'm assuming you are returning a list of links, so I'm creating an
// array of associative arrays that contain url and link name info.
// In your actual application you would probably be pulling this data from a
// database instead, using the $query variable to filter the results that the DB
// returns. I would recommend using prepared statements to avoid SQL injection
// attacks. My PHP is really rusty right now so I'm not going to attempt to
// filter this array and just return the whole thing.
$results = array(
array('name' => 'Foo', 'url' => '/foo'),
array('name' => 'Bar', 'url' => '/bar'),
array('name' => 'Baz', 'url' => '/baz'),
);
// encode our array as JSON so we can easily decode it in JavaScript
echo (json_encode($results));
?>
然后,这是您用来发出请求并显示结果的 JS。
// cache elements we will be using in variables
const searchForm = document.getElementById("search-form");
const searchQuery = document.getElementById("search-query");
const searchResults = document.getElementById("search-results");
// this function will do the XHR request and display the results
function blogSearch(event) {
// stops the default action, in this case submitting the form to the server
event.preventDefault();
// get the query and build a url to request
let query = searchQuery.value;
let url = `../list.php?q=${query}`;
let displayError = () => {
searchResults.innerHTML = '<li>There was an error retrieving your search results</li>';
};
let request = new XMLHttpRequest();
request.open('GET', url, true);
request.onload = () => {
if (this.status >= 200 && this.status < 400) {
// parse the JSON data that was returned
let data = JSON.parse(this.response);
// build up a list of li element containing links
let html = ''
data.forEach(item => {
html += `<li><a href="${item.url}">${item.name}</a></li>`;
});
// display the search results in our unordered list
searchResults.innerHTML = html;
} else {
displayError();
}
};
request.onerror = () => {
displayError();
};
request.send();
}
// attach the event to the search form
searchForm.addEventListener('submit', blogSearch, false);
关于我改变的一些事情的几点说明:
- 除非您使用 XHTML,否则您不需要自行关闭 void 元素。(即在我的代码中我使用
<input>
而不是<input />
)。 - 我使用标签而不是占位符,因为占位符用于有效输入的示例,而不是作为标签。我也使用
type="search"
了代替,text
因为这是一个搜索框。 - 我使用
addEventListener
而不是 anonsubmit
来保持关注点分离。 - 我使用了箭头函数;所有现代浏览器都支持它们(IE 不是现代的)。
- 我使用了模板文字;现代浏览器支持它们(同样 IE 不是现代的)。
- 我使用了现代
let
而const
不是var
任何远程现代浏览器都支持它们(甚至 IE 11 也支持它们)。
进一步阅读
推荐阅读
- python-3.x - 使用 Selenium web scraper for loop 将文本输出打印到单个列表中
- unison - 设置遵循 Unison 建议的操作
- io - io.netty.channel.AbstractChannel$AnnotatedConnectException:连接超时:没有更多信息:
- r - R中这两个命令有什么区别?(因子变量的水平)
- machine-learning - node2vec 的工作原理
- r - 文本的 R 特征提取
- python - 导入模块失败
- javascript - Redux:我应该将组件特定的操作放入全局 actions.js 并从顶部向下传递吗?
- vim - 如何为特定的 Vim 选项卡着色
- php - Laravel:找不到导出