如何用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
相关产品推荐
相关产品推荐

