javascript - 无法使用 URL 链接从 AJAX API 获取数据
问题描述
(我刚开始学习 JavaScript 和 AJAX)在我的项目中我需要使用 URL 链接从 AJAX API 获取数据。按钮“全部获取”插件直接工作,没有问题,但如果我需要从未在 URL 中传输的变量中找到特定的(使用搜索表单)变量。
而且我没有收到任何错误消息
附件区
variable from <input type="text"/>
not transmitted in URL
----------
<button class="nav-link" id="getAllBtn">Get All</button>
<form">
<input type="text" placeholder="Search" aria-label="Search" id="currencyid" />
<button class="btn my-2 my-sm-0" id="searchBtn">Search</button>
</form>
$("#getAllBtn").on("click", function() {
console.log("home btn clicked")
$.ajax({
url: `http://www.example.com/`,
method: "GET",
success: function(result) {
clearAll();
$("#cryptoCards").html(getCurrenciesCard(result))
},
error: function() {
clearAll();
$("#cryptoCards").html("<h5>No Data!</h5>")
}
})
});
$("#searchBtn").on("click", function() {
const currencyid = $("#currencyid").val();
console.log("input: ", currencyid);
$.ajax({
url: `http://www.example.com/${currencyid}`,
method: "GET",
success: function(result) {
clearAll();
$("#cryptoCards").html(oneCurrencyCard(result))
},
error: function() {
clearAll();
$("#cryptoCards").html("<h5>No Data!</h5>")
}
})
});
解决方案
A<button>
的类型默认为submit
- 因此您正在提交表单,因此您的任何click
操作都不会运行
最简单的解决方案是使按钮不提交表单
<form>
<input type="text" placeholder="Search" aria-label="Search" id="currencyid" />
<button type="button" class="btn my-2 my-sm-0" id="searchBtn">Search</button>
</form>
或另一种解决方案是防止默认行为
$("#searchBtn").on("click", function(e) {
e.preventDefault();
const currencyid = $("#currencyid").val();
推荐阅读
- encryption - Generating secret tenant for Salesforce Shield encryption module using Openssl, BYOK
- python - Array to be reshaped
- visual-studio - Angular-cli 项目,托管在 Visual Studio Core 2.2 Web Api 项目中,随机编译失败
- ios - 在音频引擎输入节点上安装水龙头时出错
- api - 使用从 API 调用退回的电子邮件数据下载准确的电子邮件数据
- excel - 查找最后一行,擦除标题
- sql-server - 选择什么列来创建聚集索引
- ios - TableViewCell 不显示我设置为约束的高度
- powershell - Docker dotnet 运行端口未映射,Windows 10 主机,Linux 容器
- wpf - 如何让 JAWS 屏幕阅读器按顺序读取 wpf 应用程序中的元素?