I am using JQuery .get method to retrieve some content from a webpage (page 1) and show it in a div in the main page. The problem is the content retrieved contains some javascript calls. The content is being displayed, but the Javascript methods are not getting executed. The .js file is being referenced across all the pages, so the availability of the js in the main is not a problem.
This is the code in the main page. URL of page 1 is given to the .get function:
$.get(url, function(response) {
var newContent = $(response).find("#right"); //Find the content section of the response
var contentWrapper = $("#wrap"); //Find the content-wrapper where we are supposed to change the content.
var oldContent = contentWrapper.find("#right"); //Find the old content which we should replace.
oldContent.replaceWith(newContent);
});
This is the code in the #right (div) of Page 1
Some html tags...
<p><script type="text/javascript">abc7();</script></p>
<p><script>s(30)</script></p>
Some html tags...
The functions abc7 and s are available in a .js (normal javascript file) that is being reference in the section of all pages
The s(30) should display a text field of size 30.
Inline JavaScript won't execute unless you run
eval()
on it. You can read more about that here:An
eval()
solution could look something like this, but I would consider it bad practice:A better solution is to set a identifier/name on the
#right
tag and execute the code needed for that specific content.Something like:
A simple solution that just passes the page name to a function that will execute the code depending on page would look something like this:
This keeps the JavaScript code from being inline and doesn't use
eval()
. Even better would be to use events for when page content change, but this will be enough for now.You can use
.load()
function instead of.get()
. It automatically executes the scripts that are contained in the response.Here is the documentation: .load()