【问题标题】:Get form values and pass it to Bootstrap modal on Submit获取表单值并在提交时将其传递给 Bootstrap 模式
【发布时间】:2016-07-24 02:37:58
【问题描述】:

我正在尝试获取我的表单数据并将其作为 JSON 传递给我的模态对话框,该对话框也应该在提交按钮上打开!

这是我到目前为止所做的:

HTML

<form class="form-horizontal" id="configuration-form">
--unimportant--
<button type="submit" class="btn btn-danger btn-lg" data-toggle="modal" data-target="#myModal">Submit</button>
</form>

<div id="myModal" class="modal fade" role="dialog">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                    <h4 class="modal-title">Please copy this code to your HTML</h4>
                </div>
                <div class="modal-body">
                    <code id="configurationObject"></code><br/>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                </div>
            </div>  
        </div>
    </div>

JS

(function(formId) {
    $("#" + formId).submit(function(event){
        event.preventDefault();
        var errMsg = "Something went wrong with form submit, please try again";
        var json = convertFormToJSON(this); //here I got my json object with all my form data


        $.ajax({
            type : 'POST',
            data: {conf: JSON.stringify(json)},
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success : function(data){
                $("#configurationObject").html(data);
            },
            failure: function(errMsg) {
                alert(errMsg);
            }
        });

        return false;
    });
})("configuration-form");

点击提交按钮后,我得到了带有表单数据的 JSON 对象(我可以在之后记录它

var json = convertFormToJSON(this)

我的模态对话框窗口已打开,但我确实错过了我的数据。 id="configurationObject" 的元素为空。

提前致谢

【问题讨论】:

  • 尝试查看 $("#configurationObject").html(data); 的输出在成功块中使用它之前。在进行调用之前捕获输出后,请在成功块中使用它。试一试,看看这是否有效。
  • 是的,我通过 $("#configurationObject").html(JSON.stringify(json)); 找到了类似的解决方案在ajax调用之前。我想我会这样离开它。谢谢!

标签: javascript jquery html json twitter-bootstrap


【解决方案1】:

您是否尝试将数据追加()到#configurationObject,而不是使用html()?

【讨论】:

    【解决方案2】:

    根据文档 $.html() 接受 A string of HTML to set as the content of each matched element.

    在这里,您传递的是 json data 而不是字符串。因此,首先,您必须将 json 响应转换为字符串。 $("#configurationObject").html(JSON.stringify(data));

    或者你可以使用

    $("#configurationObject").append(data);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-21
      • 2022-01-24
      • 2012-09-11
      • 2021-10-01
      相关资源
      最近更新 更多