Home > Web Front-end > JS Tutorial > Can You Call JavaScript Functions Returned from Ajax Responses?

Can You Call JavaScript Functions Returned from Ajax Responses?

Susan Sarandon
Release: 2024-10-22 20:59:02
Original
1087 people have browsed it

Can You Call JavaScript Functions Returned from Ajax Responses?

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:

  • The returned function declaration is syntactically correct.
  • The function declaration is evaluated using eval(). This executes the declaration code and makes the function available throughout the page's lifetime.

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>
Copy after login

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!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template