【问题标题】:How to send html in document.write() in ajax function?如何在 ajax 函数中的 document.write() 中发送 html?
【发布时间】:2018-04-03 23:26:22
【问题描述】:

我最近开始使用 Ajax 和 javascript。

这是我的 ajax 函数:

   var saveForm = function () {
var form = $(this);
$.ajax({
  url: form.attr("action"),
  data: form.serialize(),
  type: form.attr("method"),
  dataType: 'json',
  success: function (data) {
    if (data.form_is_valid) {

      w=window.open();
      w.document.write($("#book-table tbody").html(data.html_book_list));
      w.print();
      w.close();

      $("#book-table tbody").html(data.html_book_list);

      $("#modal-book").modal("hide");

    }
    else {
      $("#modal-book .modal-content").html(data.html_form);
    }
  }
});
return false;
};

在输出中它只显示[object Object] 并且没有通过任何html。

如何将正确的 html 传递给 document.write() 以及如何访问“数据”以执行修改?

【问题讨论】:

  • 看起来你正在尝试做同样的事情两次...$('#abc').html() 应该将所需的代码转储到目标元素 (#abc) -- 尝试只传递 data.html_book_list 而不是jQuery部分...w.document.write(data.html_book_list);(假设返回的数据有.html_book_list)
  • 然后尝试 ... w.document.write( $("#book-table tbody").html() ); -- 通过将参数传递给 .html() jQuery 想要写入数据;但如果没有参数,它应该返回选择的内容。
  • 成功了!!谢谢。
  • 有没有办法修改那个html?
  • 当然,您需要先将其分配给您的目标(正如您稍后在代码中所做的那样)。您可以创建一个函数来清理/格式化传入的数据,然后将其转储到“#book-table tbody”——然后重复您已经拥有的步骤

标签: javascript html json ajax


【解决方案1】:

$('#element').html() 返回目标中存在的内容字符串。

$('#element').html('some html') 返回添加了新代码的 HTML 对象。

$('#output').html( $('#test').html() );

// returns a string of the HTML inside
console.log( $('#test3').html() );
// returns the object being targeted
console.log( $('#test2').html('some html') );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="output"></div>

<div id="test">Test content 123</div>

<div id="test2">Test Content 456</div>

<div id="test3">Test Content 789</div>

【讨论】:

  • 你太棒了!!
  • 谢谢 :) 乐于助人
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-25
相关资源
最近更新 更多