从ajax调用执行动态javascript

时间:2022-03-25 09:23:17

I have a web application that is powered by ASP.NET on the server side and Javascript/jQuery on the client side. I'd like to know if it's possible to make an Ajax call to an ASP.NET WebMethod and have the returned javascript code executed. For example (very simplified example):

我有一个Web服务器,由服务器端的ASP.NET和客户端的Javascript / jQuery提供支持。我想知道是否可以对ASP.NET WebMethod进行Ajax调用并执行返回的javascript代码。例如(非常简化的例子):

My HTML:

<html>
    <head>
        <title></title>
    </head>
    <body>
        <div id="divMessage"></div>
    </body>
</html>

In my C#:

在我的C#中:

[WebMethod]
public static string GetScriptCode()
{
    return "$('#divMessage').html('This is a test');";
}

In my javascript:

在我的javascript中:

$(function() {
    var handler = function(msg) {
        var myScriptCode = msg.d;
        // I'd like $('#divMessage') to contain my message
    };

    $.ajax({
        type: "POST",
        url: "Test.aspx/GetScriptCode",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: handler
    });
});

I'd like the javascript that is returned from my GetScriptCode() to execute. Any ideas how to do this?

我想要从我的GetScriptCode()返回的javascript来执行。任何想法如何做到这一点?

1 个解决方案

#1


0  

using eval() is one option, but as everyone say eval is evil, don't use it.

使用eval()是一种选择,但正如每个人都说eval是邪恶的,不要使用它。

I normally do it using a dynamic function like so:

我通常使用动态函数这样做:

var theCode = "$('#divMessage').html('This is a test');";

var F=new function (theCode);

return(F());

Sort of looks like reinventing the eval, but that's how I do it as of now.

看起来像重新发明eval,但这就是我现在这样做的方式。

#1


0  

using eval() is one option, but as everyone say eval is evil, don't use it.

使用eval()是一种选择,但正如每个人都说eval是邪恶的,不要使用它。

I normally do it using a dynamic function like so:

我通常使用动态函数这样做:

var theCode = "$('#divMessage').html('This is a test');";

var F=new function (theCode);

return(F());

Sort of looks like reinventing the eval, but that's how I do it as of now.

看起来像重新发明eval,但这就是我现在这样做的方式。