Executing Javascript written with XMLHttpRequest that contains script tags?

故事扮演 提交于 2019-12-18 18:04:27

问题


Through a Javascript request, XMLHttpRequest responds with some additional Javascript that needs to be added to the page the requesting page.

Using eval(), if the response is something like:

alert('This is the js response');

... then this works just fine.

However, the text returned could look something like this:

<script language="javascript">var checkVar='checkVar: value 1';</script>

but most likely:

<script src="http://www.somesite.com/setCheckVarValue.js"></script> 

... where additional JS needs to be loaded on the page.

I have ensured that the XMLHttpRequest is synchronous, as I want to reference checkVar right after this.

So:

<script type="text/javascript" src="http://www.mysite.com/addJSToPage.js" />
// at this point, since this is a synchronous call, page processing waits
// until the response is received that needs to include the additional JS
// to load; this, for testing sets the value of checkVar

<script type="text/javascript" >
    alert(checkVar);
</script>

The alert message should read "checkVar: value 1".

For other reasons, this is not just as simple as setting var checkVar in addJSToPaged.js, so I'm not looking for that kind of recommendation.

I'm using alert(checkVar) simply as a test to ensure that a value has been set through JS in the response.

I suppose that I could strip out the beginning and ending script tags and keep the eval() way of doing it. However, I would like to know if there are any solutions that support what I'm looking for?

Thanks.

UPDATE

Following Prashanth's suggestion, in addJSToPage.js I added:

var dynamicElement = document.createElement('div');

Then in the response from the XMLHttpRequest, I did:

dynamicElement.appendChild = xmlhttp.responseText;

Still not seeing the value of checkVar.


回答1:


Ignoring the fact that whatever you are doing is probably a bad idea, Prashanth has the right idea of inserting it into the DOM. you could also strip out the tags and just eval as "normal".

Not ignoring the fact that 1) eval is evil, 2) dynamically loading remote code is bad and 3) synchronous AJAX is extra bad, I have this to say:

Unless you know what you are doing, evaling anything is a bad idea, its hard to debug, can expose massive security flaws and all sorts of other nasties. You then compound this by loading remote code, which is apparently generated in a way outside of your control because you aren't able to get just the script. Synchronous Ajax is bad because there is only one thread in javascript, blocking on Ajax will literally lock up the entire page until it is loaded because even things like scrolling generate javascript events, which the currently busy engine has to check for handlers. While the request goes fast on your local machine, someone with a slow or poor quality connection could be waiting a while, up to the timeout time for the connection. The 'A' in AJAX is asynchronous, and for a good reason, use the callbacks, they are there for a reason.

If you are just doing data passing, use JSON, which is JavaScript Object Notation, a simple data format that happens to also be valid JavaScript. You can use eval on it, but I suggest a JSON parser, i think most modern browsers have them built in (could be wrong here). JSON is good because it can express complex data structures, is simple to generate and parse and is widely supported.




回答2:


Recapping - the need is present to be able to dynamically load some content onto a page after/during load, and have it execute. By execute, I don't just mean change the text on some div - that's easy. But if we want to load some new JS dynamically, say an alert that comes from some outside source, and inject it, along with it's script tags, and maybe some other HTML code, then the solution is to use the following jQuery call:

jQuery(dynamicResponse).appendTo('body');

dynamicResponse comes from an asynchronous $.ajax({}) or XmlHttpRequest response. Once present, it is appended onto whatever DOM element, specified in appendTo() and executed.




回答3:


Here is the example

var script = document.createElement("script");
//innerHTML can be the response from your server. But send the text with script tag.
script.innerHTML = "var foo = function(){console.log('injected into the DOM')}" 
document.body.appendChild(script) // insert into the DOM
foo() // call the function 


来源:https://stackoverflow.com/questions/9107847/executing-javascript-written-with-xmlhttprequest-that-contains-script-tags

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!