Calling JavaScript Functions Returned from Ajax Responses
In many systems, Ajax requests return script blocks containing functions that need to be called after data insertion. This raises the question of whether such functions are callable after being inserted into a DIV.
Is it Possible?
Yes, calling returned JavaScript functions is possible, assuming:
Example Code:
The following code illustrates the concept without using Ajax:
<code class="javascript">var newsc = '<script id="sc1" type="text/javascript">function go() { alert("GO!") }</script>'; var e = document.getElementById('div1'); e.innerHTML = newsc; eval(document.getElementById('sc1').innerHTML);</code>
Considerations:
While you can externalize the function into a separate .js file, it may cause issues with repeated Ajax invocations or function context changes. Therefore, carefully consider your design choices.
Alternative Approach:
If you need context-aware invocation of the function immediately after receiving the Ajax response, it's recommended to use the Prototype approach described by krosenvold. It's cross-browser, tested, and provides a solid foundation for future implementations.
The above is the detailed content of Can You Call JavaScript Functions Returned from Ajax Responses?. For more information, please follow other related articles on the PHP Chinese website!