javascript - 如何在ajax请求后自动选择html输入中的 "select"选项?

标签 javascript php jquery html ajax

我有一个 AJAX 请求发送到我的 PHP 文件,以从与用户相关的数据库中提取数据。我想自动填充表单输入。我能够填写大部分输入,但 HTML“选择”选项确实难住了我。有谁知道如何自动选择数据库中的值?
HTML

<select class="gender-reg" name="gender-reg">
    <option value="male">Male</option>
    <option value="female">Female</option>
    <option value="optout">Rather Not Say</option>
</select>

AJAX 请求

$(function () {
    $.ajax({
        type: 'GET',
        url: 'http://localhost:8090/HELPERSITE/src/php/session.php',
        dataType: 'json',
        data: '',
        success: function (response) {
            console.log(response);
            $(".username-reg").attr("value", (response['username']));
            $(".pwd-reg").attr("value", (response['password']));
            $(".email-reg").attr("value", (response['email']));
            $(".acct-type").text(response['type']);
            $(".fname-reg").attr("value", (response['fname']));
            $(".lname-reg").attr("value", (response['lname']));

            $(".gender-reg").attr("value", (response['gender']));

            $(".street-reg").attr("value", (response['street']));

        }
    })
});

最佳答案

您可以简单地使用 .val() :

$(".gender-reg").val(response['gender']);

关于javascript - 如何在ajax请求后自动选择html输入中的 "select"选项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60595050/

相关文章:

javascript - 在 React 元素中将 videojs 播放器放入 16/8 div

php - 计算循环内的确切 sleep 时间

javascript - Facebook 社交插件无法在 PHP 中使用 JavaScript 分页?

Javascript 加载图标无法在浏览器上禁用 JS 的情况下使用

javascript - 如果未选中复选框则禁用链接

php - 未选中的复选框返回空值

javascript - 可以在unity js脚本中使用javascript套接字客户端吗?

javascript将函数传递给onclick事件

php - Mysql:将 3 个表与多个 'where' 连接起来?

java - 点击 map 获取多个坐标