简体   繁体   English

在Ajax响应中加载HTML

[英]Loading HTML in the Ajax Response

So I am dealing with this weird service when returns a html page as the ajax response which has a form and the form is triggered automatically by some scripts in the page (so when you render the page a post request will be sent to you). 因此,当返回一个HTML页面作为具有表单的ajax响应,并且表单由页面中的某些脚本自动触发时,我正在处理这种奇怪的服务(因此,在呈现页面时,将向您发送发布请求)。 What I am trying to do is to load this page I am getting from the response. 我想做的是加载我从响应中得到的页面。

Say this is my Ajax call: 说这是我的Ajax电话:

var ajax_call_test = function() {
    var formData = new FormData($('#documentForm')[0]);
    console.log("doc form: " + formData);

    $.ajaxSetup({
        xhrFields: {
            withCredentials: true
        }
    });

    $.ajax("/documents/upload/", {
        type: 'POST',
        data: formData,
        processData: false,
        contentType: false,
        cache: false,
        async: false,
        dataType: 'html',
        success: function(html){
            // ?
        },
        error: function(jqXHR, textStatus, errorThrown) {
            console.log("failed: " + errorThrown);
        }
    });
}

So I tried to use .html to set the response to a hidden <div> . 因此,我尝试使用.html将响应设置为隐藏的<div> It sets the html but never triggers the form. 它设置html,但从不触发表单。 I am guessing the javascript in that page is not loaded when I use .html . 我猜测当我使用.html时,该页面中的javascript无法加载。

I also cannot use jQuery.parseHTML() since the version of library I am using does not support that functionality. 我也不能使用jQuery.parseHTML()因为我使用的库版本不支持该功能。 Any idea what should I do with response? 知道我该如何应对吗?

When ever you load new html into the DOM. 每当您将新的html加载到DOM中时。 The javascript does not know about it. javascript对此一无所知。

I have to re invoke my javascript to work with the new DOM. 我必须重新调用我的JavaScript才能使用新的DOM。

Lets say I have some click events 可以说我有一些点击事件

$(function(){invokeClicks()}) // onload call

function invokeSomeAction(){
    $("selector").off(); // disable previous events from old html
    $("selector").on("event", function(){
        // handle event
    })
}

function invokeClicks(){
    invokeSomeAction();
    // ... etc
}

So when this JS loads, the invokeClicks() method gets called. 因此,在加载此JS时,将invokeClicks()方法。

Now, if I replace the HTML through a $.ajax() call, all I have to do is call invokeClicks() again to clear the old events and now the new HTML will work with the javascript 现在,如果我通过$.ajax()调用替换了HTML,那么我要做的就是再次调用invokeClicks()清除旧事件,现在新的HTML将可以与javascript一起使用

$.ajax({
    url: "somepath",
    data: {id: 1},
    method: "GET", 
    success: function(html){
         $("container_selector").html(html);
         invokeClicks(); // reinit
    },
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM