是否可以在新窗口中使用jQuery?

时间:2019-03-19 12:53:12

标签: javascript jquery ajax

我已经尝试解决这个问题了几个小时了,也许你们中的任何人都可以帮助我。

现在我的代码如下:

$('.clickable').on('click', function() {
  var id = $(this).attr('data-packages');
  id = "'" + id + "'";
  $.ajax({
    url: "show.php",
    data: {
      type: "showSFM",
      data: id,
      user: username
    },
    type: "POST",
    success: function(data) {
      $('#main').html(data);
    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

一切正常,但是我问自己是否可以在新Window上使用$('#main').html(data)。现在,如果单击“元素”,则当前窗口将显示结果,但我希望弹出一个新选项卡。

我正在尝试这样的事情:

success: function(data) {
  var url = location.href;
  var window = window.open(url);
  window.document.getElementById('main').innerHTML = data;
}

我得到的结果是该窗口在主页上打开。看起来window.open(url)可以正常工作,但下面的行什么也没做。

2 个答案:

答案 0 :(得分:0)

您可以在URL中发送请求所需的数据,然后在新页面上,可以再次发送AJAX请求,并从URL获取所需的数据。

答案 1 :(得分:0)

The reason this likely doesn't work is due to the fact that you use:

window.document.getElementById('main')

The window might already be opened by the line before, but is most likely not loaded and doesn't contain an element with id main yet (since making a HTTP(S) request takes time). This could be solved by moving the filling of main element into a callback.

window.addEventListener('load', function () {
  window.document.getElementById('main').innerHTML = data;
}, { once: true });