简体   繁体   English

将Javascript加载到ajax加载的内容中

[英]Load Javascript into ajax loaded content

I am new to working with AJAX and have some experience with Java/Jquery. 我刚接触AJAX,并且对Java / Jquery有一定的经验。 I have been looking around for an solution to my problem but i cant seem to find any. 我一直在寻找解决问题的方法,但似乎找不到任何方法。

I am trying to build a function in a webshop where the product will appear in a popup window instead of loading a new page. 我正在尝试在网上商店中构建功能,该产品将出现在弹出窗口中,而不是加载新页面。

I got it working by using this code: 我通过使用以下代码使其工作:

$(".product-slot a").live('click', function() {
  var myUrl = $(this).attr("href") + " #product-content";
  $("#product-overlay-inner").load(myUrl, function() {
  });
  $("#product-overlay").fadeIn();
  return false;
});

product-slot a = Link to the product in the category page. product-slot a =链接到类别页面中的产品。
product-content = the div i want to insert in the popup from the product page. product-content =我要在产品页面的弹出窗口中插入的div。
product-overlay-inner = The popup window. product-overlay-inner =弹出窗口。
product-overlay = The popup wrapper. product-overlay =弹出包装器。

The problem that i now have is that my Javascript/Jquery isnt working in the productpopup. 我现在遇到的问题是我的Javascript / Jquery在productpopup中不起作用。 For example the lightbox for the product image or the button to add product to shoppingcart doesnt work. 例如,产品图片的灯箱或将产品添加到购物车的按钮不起作用。 Is there anyway to make the javascript work inside the loaded content or to load javascript into the popup? 无论如何,有没有办法使javascript在加载的内容中起作用或将javascript加载到弹出窗口中?

I hope you can understand what my problem is! 希望您能理解我的问题所在!

Thank you in advance! 先感谢您!

EDIT: The platform im using has jquery-ui-1.7.2 编辑:使用的平台即时通讯有jquery-ui-1.7.2

I know this is an old thread but I've been working on a similar process with the same script loading problem and thought I'd share my version as another option. 我知道这是一个旧线程,但是我一直在使用相同的脚本加载问题进行类似的过程,并认为我将共享我的版本作为另一个选择。

I have a basic route handler for when a user clicks an anchor/button etc that I use to swap out the main content area of the site, in this example it's the ".page" class. 我有一个基本的路由处理程序,用于当用户单击锚点/按钮等时用来交换站点的主要内容区域,在此示例中为“ .page”类。

I then use a function to make an ajax call to get the html content as a partial, at the moment they are php files and they do some preliminary rendering server side to build the html but this isn't necessary. 然后,我使用一个函数进行ajax调用,以部分获取html内容,目前它们是php文件,并且它们进行了一些初步的呈现服务器端来构建html,但这不是必需的。

The callback handles placing the new html and as I know what script I need I just append it to the bottom in a script tag created on the fly. 回调处理新html的放置,并且我知道我需要什么脚本,我只需将其附加到动态创建的script标签的底部即可。 If I have an error at the server I pass this back as content which may be just a key word that I can use to trigger a custom js method to print something more meaningful to the page. 如果我在服务器上遇到错误,则将其作为内容传递回去,它可能只是一个关键词,可以用来触发自定义js方法以将更有意义的内容打印到页面上。

here's a basic implementation based on the register route handler: 这是基于注册路由处理程序的基本实现:

var register = function(){
    $(".page").html("");
    // use the getText ajax function to get the page content:
    getText('partials/register.php', function(content) {
        $(".page").html(content);
        var script = document.createElement('script');
        script.src = "js/register.js";
        $(".page").append(script);
    });
};




/******************************************
 * Ajax helpers
 ******************************************/
// Issue a Http GET request for the contents of the specified Url.
// when the response arrives successfully, verify it's plain text
// and if so, pass it to the specified callback function
function getText(url, callback) {
    var request = new XMLHttpRequest();
    request.open("GET", url);
    request.onreadystatechange = function() {
        // if the request is complete and was successful -
        if (request.readyState === 4 && request.status === 200) {
            // check the content type:
            var type = request.getResponseHeader("Content-Type");
            if (type.match(/^text/)) {
                callback(request.responseText);
            }
        }
    };
    // send it:
    request.send(null); // nothing to send on GET requests.
}

I find this a good way to 'module-ize' my code into partial views and separated JavaScript files that can be swapped in/out of the page easily. 我发现这是一种将代码“模块化”为部分视图和分离的JavaScript文件的好方法,这些文件可以轻松地在页面中进行换入/换出。 I will be working on a way to make this more dynamic and even cache these 'modules' for repeated use in an SPA scenario. 我将研究一种使这种方法更加动态的方法,甚至缓存这些“模块”以在SPA场景中重复使用。

I'm relatively new to web dev so if you can see any problems with this or a safer/better way to do it I'm all ears :) 我是Web开发人员的新手,因此,如果您能看到此问题或采用更安全/更好的方法,将会非常感激:)

Yes you can load Javascript from a dynamic page, but not with load() as load strips any Javascript and inserts the raw HTML. 是的,您可以从动态页面加载Javascript,但不能通过load() load因为load剥离任何Javascript并插入原始HTML。

Solution: pull down raw page with a get and reattach any Javascript blocks. 解决方案:使用get下拉原始页面并重新附加任何Javascript块。

Apologies that this is in Typescript, but you should get the idea (if anything, strongly-typed TypeScript is easier to read than plain Javascript): 抱歉,这在Typescript中,但是您应该了解一下(如果有的话,强类型TypeScript比普通Javascript更易于阅读):

    _loadIntoPanel(panel: JQuery, url: string, callback?: { (): void; })
    {
        // Regular expression to match <script>...</script> block
        var re = /<script\b[^>]*>([\s\S]*?)<\/script>/gm;
        var scripts: string = "";
        var match;

        // Do an async AJAX get
        $.ajax({
            url: url,
            type: "get",
            success: function (data: string, status: string, xhr)
            {
                while (match = re.exec(data))
                {
                    if (match[1] != "")
                    {
                        // TODO: Any extra work here to eliminate existing scripts from being inserted
                       scripts += match[0];
                    }
                }

                // Replace the contents of the panel
                //panel.html(data);

                // If you only want part of the loaded view (assuming it is not a partial view)
                // using something like
                panel.html($(data).find('#product-content'));

                // Add the scripts - will evaluate immediately - beware of any onload code
                panel.append(scripts);

                if (callback) { callback(); }
            },
            error: function (xhr, status, error)
            {
                alert(error);
            }
        });
    }

Plain JQuery/Javascript version with hooks: 带有钩子的普通JQuery / Javascript版本:

It will go something like: 它将类似于:

    var _loadFormIntoPanel = function (panel, url, callback) {
        var that = this;
        var re = /<script\b[^>]*>([\s\S]*?)<\/script>/gm;
        var scripts = "";
        var match;
        $.ajax({
            url: url,
            type: "get",
            success: function (data, status, xhr) {
                while(match = re.exec(data)) {
                    if(match[1] != "") {
                        // TODO: Any extra work here to eliminate existing scripts from being inserted
                        scripts += match[0];
                    }
                }
                panel.html(data);
                panel.append(scripts);
                if(callback) {
                    callback();
                }
            },
            error: function (xhr, status, error) {
                alert(error);
            }
        });
    };

$(".product-slot a").live('click', function() {
    var myUrl = $(this).attr("href") + " #product-content";
    _loadFormIntoPanel($("#product-overlay-inner"), myUrl, function() {
         // Now do extra stuff to loaded panel here
    });
  $("#product-overlay").fadeIn();
  return false;
});

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

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