【问题标题】:how do i get radio button value in ajax?如何在 ajax 中获取单选按钮值?
【发布时间】:2021-12-31 14:08:08
【问题描述】:

这是我在 php 文件中的搜索按钮。我不知道如何将单选按钮链接到js文件。

<button id="submit">Search</button> 

这是 js 文件开始的地方

var xhr = new XMLHttpRequest();

function link_events() {
xhr.addEventListener("readystatechange", showFile, false);
xhr.open("GET", "un.xml");
xhr.send();
}
function showFile() {
var outstring = "<table><tr><th>Name</th><th>Population</th><th>Area</th></tr>";
var i;

if (xhr.readyState == 4 && xhr.status == 200){
   var countries = xhr.responseXML.getElementsByTagName("country");
}

}

【问题讨论】:

  • 您需要向我们展示一下单选按钮 HTML 代码,以及到目前为止您尝试过的内容
  • 这是我的html
    非洲
    澳大利亚/大洋洲
    欧洲。

标签: javascript php html ajax xml


【解决方案1】:

您的表单中的 html 语法不正确。应该是这样的:

<form name="continent">
    <label>
        <input type="radio" name="continent" value="Africa">
        Africa
    </label>
    <br/>
    <label>
        <input type="radio" name="continent" value="Australia/Oceania">
        Australia/Oceania
    </label>
    <br/>
    <label>
        <input type="radio" name="continent" value="Europe">
        Europe.
    </label>
    <br/>
    <button id="submit">Search</button>
</form>

您可以使用 Jquery 获取所选电台的值,并使用ajax 提交表单。

在标签下面添加这段代码:

<script>
    const myForm = $('form[name="myForm"]');
    myForm.submit(function (e) {
        e.preventDefault(); // avoid to execute the actual submit of the form
        // Get value of selected radio
        let dataFormRadio = $('input[name="continent"]:checked').val();
        $.ajax({
            method: "GET",
            url: "/your-url.php",
            data: {continent: dataFormRadio}
        })
            .done(function (res) {
                console.log('request successful')
            })
            .fail(function (res) {
                console.log('request failed')
            });
    });
</script>

【讨论】:

    猜你喜欢
    • 2011-01-09
    • 2013-10-15
    • 1970-01-01
    • 2021-08-26
    • 1970-01-01
    • 2016-07-03
    • 1970-01-01
    • 2020-11-12
    • 2016-10-11
    相关资源
    最近更新 更多