当前位置: 动力学知识库 > 问答 > 编程问答 >

asp.net mvc - Dynamically writing Javascript code?

问题描述:

I am creating dynamic sites with the same code base, where I will need to display the appropriate Google ads Javascript code, based on some logic.

In my .Net 4, MVC3 environment, I have setup the following scenario:

Navigating to www.mysite.com/script_processor/ returns the following text:

function doAlert(v1, v2){alert('Called alert()' + v1 + ' : ' + v2);}

This text come out of my model as such:

page.stringResponse = "function doAlert(v1, v2){alert('Called alert()' + v1+ ' : ' + v2);}";

I can then do something like this from a separate site/page:

<script type="text/javascript" src="http://mysite.com/script_processor/">

</script>

<script type="text/javascript">

doAlert('string 1', 'string 2');

</script>

As you would expect, I get an alert box with "Called alert() string 1 : string 2", so the function on mysite.com is accessible from site 2.

Obviously when I do a view source form the page, I only see the doAlert() call, and not the content of the function that sits on mysite.com.

Now, instead of doAlert() on mysite.com, I want to have a function that dynamically writes out javascript that can will be seen on site 2 when it's called.

I created a model method:

public GetResponsePage GetPageResponse(string V1, string V2)

{

var page = new GetResponsePage();

page.stringResponse = "<script type=\"text/javascript\">document.write('testing injected Javascript.');alert('value of v1: " + V1 + "value of v2: " + V2 + "');</script>";

return page;

}

When navigating to the route, I see the popup, and the "testing injected Javascript." on the page.

When I reference this from site 2, I don't see the popup, nor do I see "testing injected Javascript" in the page source.

As I mentioned I will later replace this with the JS code for the appropriate Google Ads js code.

I don't think this is working quite right... what am I missing?

Thanks.

网友答案:

You can use the ever evil eval to dynamically execute JavaScript. The JavaScript you pass in can also declare functions.

eval("function doAlert(v1, v2){alert('Called alert()' + v1 + ' : ' + v2);}");

I'm not sure exactly what you're trying to accomplish, but you could put an eval call like this wherever you want:

function createDoAlertFunction(){
    eval("function doAlert(v1, v2){alert('Called alert()' + v1 + ' : ' + v2);}");
}

Just note though, that this should be avoided. Stick to declaring your functions the old fashioned way, like you already are.

EDIT

Oh, you want MVC to to inject JavaScript dynamically. MVC has a JavaScriptResult, but it looks like its use is strongly, strongly discouraged.

Nonetheless, here's a link that shows its use

public ActionResult DoSomething() {  
   string s = "$('#some-div').html('Updated!');";  
   return JavaScript(s);  
}  

and why it's not a good idea

分享给朋友:
您可能感兴趣的文章:
随机阅读: