简体   繁体   中英

JQuery .replaceWith function only provides raw html

I'm having small problem on my ajax response that return raw html and no script is executed, hence raw html is provided without jquery ui scripts executed.

Here are the details:


I am currently on ASP.NET MVC, I would like to communicate with
server to fet data somewhere, and return in terms of object.

Razor able to handle the model and display the data for me.

I need jquery for the tab functionality, helpful for organize data.


The Problem

Before I call ajax response, the jquery runs perfectly as shown image below:

在此处输入图片说明

I can access each tabs by clicking the header, and it provides different details. This is 100% copied from official jquery documentation for tabs as shown here

When I click the submit button it will call get request to the server and handle the data. Now I can update the details based on newer data. But when I try to click submit it returns this:

在此处输入图片说明

As seen here, it broke the jquery script hence just showing what's inside the html code.

I can assure the problem is not on the jquery, as I have tested to display form when clicked as shown here. Note the code below doesn;t reflect image above as before click normal response , it would not show the details like first picture.

string disp = "none";
if (ViewBag.Message == "AJAX")
{
    disp = "block";
}

<div id="timetableList" style="display: @disp">

This means that the updated with new data. So the problem is not inside the jquery. What the ajax did is to replace the div from old data to new data as shown here:

var ajaxFormSubmit = function () {
    var $form = $(this);
    var options = {
        url: $form.attr("action"),
        type: $form.attr("method"),
        data: $form.serialize()
    };

    $.ajax(options).done(function (data) {
        var $target = $($form.attr("data-otf-target"));
        var $newHtml = $(data);
        $target.replaceWith($newHtml);
        $newHtml.effect("highlight");           
    });

    return false;
};

In here the .done(function (data)) , data passed is the new html that has been updated, I checked it while debugging:

在此处输入图片说明

"\r\n<div id=\"timetableList\">\r\n <ul>\r\n <li><a href=\"#tabs-1\">Nunc tincidunt</a></li>\r\n <li><a href=\"#tabs-2\">Proin dolor</a></li>\r\n <li><a href=\"#tabs-3\">Aenean lacinia</a></li>\r\n </ul>\r\n ......

We can say that ajax will replace the data with new html but doesn't execute the jquqry as shown above. Is there a way so that it load scripts so that can show the result as expected.

Thanks in advance

Hey you can simply call the tabs method in ajax response function just after replaceWith method. something

$("your tabs element id").tabs()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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