繁体   English   中英

包含个人信息字段的表单还声明,城市从 api 获取数据......如何让他们一起工作而不提交表单

[英]A form having fields for personal info And also states, Cities fetching data from api... How to Make them work all togather without submitting form

上下文我创建了一个表单,它正在获取用户数据,如他们的姓名、电话号码、地址......

对于地址,我使用的是 api,它在选择特定的 state 后将州和城市提取到下拉列表中......

我已经完成了 state 部分,因为它不需要提交请求请求

现在,问题是......为了获取城市,我尝试了 jquery 和 ajax,但这需要一个帖子请求,我也有表单的其他详细信息,所以我如何让城市下拉获取所选 state 的数据而不提交表格(POST 请求)? 由于嵌套形式在 html 中不起作用,我很难找到解决方案。

请帮我解决这个问题..

您应该在用户触发的事件上调用 fetch/ api 来获取城市数据,而 UI 元素在您的情况下应该是状态下拉/选择的 onChange 事件。

const stateSelector = document.querySelector('.stateSelect');

stateSelector.addEventListener('change', function(e) {
    getCitiesForState(e.target.value);
});

function getCitiesForState(state) {
    fetch(`http://exapleapitogetallcitiesinstate/${state}`, {
        "method": "GET",
    })
    .then(response => response.json())
    .then(data => {
        console.log("cities data", data)
        // show cities dropdown, populate options in the select with the data
    })
    .catch(err => {
      console.log(err)
    });
}

你可以使用 jquery 而不是香草 js

用于事件处理https://api.jquery.com/change/#example-0

并使用https://api.jquery.com/jquery.get/获取数据

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM