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!