为什么我无法使用jQuery动态地将HTML添加到页面中?

PHP*_*Fan -1 html javascript ajax jquery twitter-bootstrap

我遵循Bootstrap Modal对话框的HTML代码:

<div class="modal fade" id="rebateModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
        <h4 class="modal-title">Submit Form</h4>
      </div>
      <div class="modal-body">
        <p style="text-align: justify;"><span style="font-weight: 700;"></p>  
        <br/>
        <!-- Here I want to dynamically add the HTML from AJAX response -->
        <form id="request_form" method="post" class="form-horizontal" action="">
        </form>
      </div>
    </div>
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)

在上面的代码中,我想在之后动态添加HTML代码

<div class="modal-body">
  <p style="text-align: justify;"><span style="font-weight: 700;"></p>  
  <br/>
Run Code Online (Sandbox Code Playgroud)

使用jQuery AJAX.

为此,我尝试下面的代码:

$('#request_form').submit(function(e) {
  var form = $(this);

  var formdata = false;

  if(window.FormData) {
    formdata = new FormData(form[0]);
  }

  var formAction = form.attr('action');

  $.ajax({
    url         : 'xyz.php',
    type        : 'POST',    
    cache       : false,
    data        : formdata ? formdata : form.serialize(),
    contentType : false,
    processData : false,

    success: function(response) {alert(response);
        // Below variable contains the HTML code that I want to add after <br/>

        var htmlString = "<div class='alert alert-danger alert-dismissible' role='alert'><button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;</button>"+response+"</div>"

        $(htmlString).insertBefore('div.modal-body:first-child');

    }
  });
  e.preventDefault();
});
Run Code Online (Sandbox Code Playgroud)

但我无法这样做.在控制台中获取错误

ReferenceError: htmlString is not defined
Run Code Online (Sandbox Code Playgroud)

Bootstrap模式中没有新的HTML.

该变量response包含以下字符串:

Id can't be blank<br>Please select Date<br>Image can't be blank<br>
Run Code Online (Sandbox Code Playgroud)

请帮助我这方面.

hai*_*770 5

  • htrmlString不是 htmlString.

  • 选择器div.modal-body:first-child将不匹配任何元素,因为div.modal-body它不是其容器的第一个子元素.据我所知,你只有一个,.modal-body你可以删除:first-child伪选择器.

    试试这个:$(htmlString).insertBefore('div.modal-body');.

根据你的评论:

如果您需要在模式中的表单之前插入内容,请尝试以下操作:

$(htmlString).insertBefore('div.modal-body #request_form');
Run Code Online (Sandbox Code Playgroud)