You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用JavaScript从API获取值并设置为输入框的默认值

将API获取的变量设置为HTML输入框默认值

问题描述

我通过JavaScript的fetch API获取到了merchant_name变量,想把它设为HTML输入框的默认值,但不知道怎么实现。

现有JavaScript代码:

fetch("http://127.0.0.1:8000/vcl/retrieve/"+url, {
          method: "GET",
          headers: {
            "Content-Type": "application/json"
          },
        }).then((res) => res.json()).then((response) => {  
          console.log (response);
          const merchant_name = response[0].merchant_name;
          console.log(merchant_name);

        })

对应的HTML输入框:

<input type="text" id="mobileNumber" class="input" value="merchant_name" required>

解决方法

你只需要在获取到merchant_name后,找到对应的输入框元素并修改它的value属性即可,步骤如下:

  • 获取输入框元素:通过document.getElementById根据输入框的id(这里是mobileNumber)获取DOM元素
  • 设置输入框默认值:在fetch的第二个then回调里,把merchant_name赋值给输入框的value属性
  • 可选:处理异常情况:添加catch捕获请求失败的情况,避免代码报错中断

修改后的完整代码

JavaScript代码:

fetch("http://127.0.0.1:8000/vcl/retrieve/"+url, {
  method: "GET",
  headers: {
    "Content-Type": "application/json"
  },
})
.then((res) => res.json())
.then((response) => {  
  console.log(response);
  const merchant_name = response[0].merchant_name;
  console.log(merchant_name);
  // 获取输入框并设置默认值
  const inputElement = document.getElementById('mobileNumber');
  if (inputElement) {
    inputElement.value = merchant_name;
  }
})
.catch((error) => {
  console.error('请求失败:', error);
});

HTML代码(初始value可省略,会被JS覆盖):

<input type="text" id="mobileNumber" class="input" required>

内容的提问来源于stack exchange,提问作者Nosi Ishmael

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 16:52:22