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

Why I'm not able to dynamically add the HTML to the page using jQuery?

本文关键字:动态 HTML 添加 jQuery 为什么      更新时间:2023-09-26

我有以下引导模式对话框的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>

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

<div class="modal-body">
  <p style="text-align: justify;"><span style="font-weight: 700;"></p>  
  <br/>

使用 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();
});

但我做不到。在控制台中获取错误为

ReferenceError: htmlString is not defined

Bootstrap modal 中没有新的 HTML。

变量response包含以下字符串:

Id can't be blank<br>Please select Date<br>Image can't be blank<br>

请在这方面帮助我。

  • 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');