执行从AJAX响应(PHP)返回的javascript函数

时间:2021-08-13 23:59:07

I am trying to load a javascript function once Ajax has returned the HTML code through PHP. This requires me to echo the javascript in the ajax response.

一旦Ajax通过PHP返回HTML代码,我试图加载一个javascript函数。这需要我回应ajax响应中的javascript。

In other words i am trying to add this code (placed between script tags) in the PHP Ajax response.. hoping that it executes

换句话说,我试图在PHP Ajax响应中添加此代码(放在脚本标记之间)..希望它执行

$('#green').smartpaginator({ Some code... });

From what I have read so far the browser has done reading the Javascript and will not execute this. Is there a way to do this.... ?

从我到目前为止所读到的浏览器已经完成了阅读Javascript并且不会执行此操作。有没有办法做到这一点.... ?

1 个解决方案

#1


19  

You have to Evaluate that code like this

你必须像这样评估那些代码

eval("("+response+")");

OR

要么

If your response contains both html and javascript code you have to do like this

如果你的回复包含html和javascript代码,你必须这样做

 $.ajax({
            url: "/snippets/js-in-ajax-response.html",
            context: document.body,
            success: function(responseText) {
                $("#response-div").html(responseText);
                $("#response-div").find("script").each(function(i) {
                    eval($(this).text());
                });
            }
        });

#1


19  

You have to Evaluate that code like this

你必须像这样评估那些代码

eval("("+response+")");

OR

要么

If your response contains both html and javascript code you have to do like this

如果你的回复包含html和javascript代码,你必须这样做

 $.ajax({
            url: "/snippets/js-in-ajax-response.html",
            context: document.body,
            success: function(responseText) {
                $("#response-div").html(responseText);
                $("#response-div").find("script").each(function(i) {
                    eval($(this).text());
                });
            }
        });