首页 > 解决方案 > 无法使用 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>")
        }
    })
});

标签: javascriptjqueryajax

解决方案


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();

推荐阅读