Home  >  Article  >  Web Front-end  >  How to Invoke JavaScript Functions Returned from an Ajax Response?

How to Invoke JavaScript Functions Returned from an Ajax Response?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-22 13:27:02815browse

How to Invoke JavaScript Functions Returned from an Ajax Response?

Executing JavaScript Functions Returned from an Ajax Response

Your request involves retrieving a JavaScript function as part of an Ajax response and subsequently calling it to perform certain actions. To accomplish this, it's important to consider the following aspects:

Function Availability

Once the Ajax response containing the JavaScript function is inserted into the target DIV element, the function becomes available for execution on that page.

Function Declaration

The function declaration within the JavaScript code returned by the Ajax callback must be syntactically correct. This ensures the browser can interpret the declaration code.

Function Execution

Even though the function declaration is present in the DIV element, it remains unexecuted, and the browser is unaware of its existence. To call the function, you must evaluate its declaration code using the eval() function.

Example

The following code demonstrates how to evaluate the declaration code and make the function callable:

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);

This example inserts the JavaScript function declaration into a DIV element and evaluates it, making the go() function available for execution.

Execution Timing

It's important to note that the function is available for invocation only after the evaluation process is complete. The exact timing may vary depending on the Ajax implementation and response handling.

The above is the detailed content of How to Invoke JavaScript Functions Returned from an Ajax Response?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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