如何在成功的 jQuery AJAX 请求后重新渲染表单数据

我有一个从 Luci 动态渲染的模板。如果修改了任何字段,点击保存时,我会进行 jQuery AJAX post 调用,更新后端数据并返回回调的响应。

如果在加载视图后更改了任何字段,则会通过比较默认值与当前值来更改字段的颜色,并在再次输入原始值时重新设置颜色。从 jquery 中获取默认值。

// 修改已修改字段的颜色
$("input").on("keyup mouseup", function () {
    var fieldType = $(this).attr("type");
    if (fieldType === "text" || fieldType === "password") {
       if ($(this)[0].defaultValue !== $(this)[0].value) {
          $(this).css("background-color", "#ffc");
       } else {
          $(this).css("background-color", "white");
       }
    }
});

目前,视图显示新值,因为页面不重新加载。我期望只有视图(表单数据)以新值重新呈现,因为更改的字段仍然设置了 #ffc 颜色。 我还需要更新输入标记的 defaultValue 的新值。

我如何在不重新加载页面的情况下重新渲染表单?

我的 html 页面样本

<%-
local uci = require("luci.model.uci")
function generateRowsFunc()
    local itr = 0
    uci:foreach('accounts','account',
        function(section)
            write('<tr><td><input type="text" name="full_name_'..itr..'" value="'..section["full_name"]..'"></td>'..
                '<td><input type="text" name="username_'..itr..'" value="'..section["username"]..'"></td>'..
                '<td><input type="password" name="password_'..itr..'" value="'..section["password"]..'"></td></tr>')
        end
    )
end
-%>
<%+header%>

<div class="cbi-section row-section">
    <form name="saveSetting">
        <div>
            <table class="custom-table">
                <thead>
                    <tr>
                        <th>选择</th>
                        <th>全名</th>
                        <th>用户名</th>
                        <th>密码</th>
                    </tr>
                </thead>
                <tbody>
                    <% generateRowsFunc() %>
                </tbody>
            </table>
        </div>
    </form>
    <input type="button" id="save" value="<%:保存%>" class="cbi-login-button">
    <input type="reset" id="cancel" value="<%:取消%>" class="cbi-login-button">
</div>

<%+footer%>

我的 jQuery 示例

$("#save").click(function () {
    $.ajax({
        type: 'POST',
        url: 'save',
        data: $('form[name="saveSetting"]').serializeArray();,
        success: function (res) {
            console.log("Ajax success", res); // 保存成功
        },
        error: function (err) {
            console.log("Ajax failed", err);
        }
    });
});
点赞