1

I want to download some html from an external source, and get only the contents within id #lay_body_get. This external source also contains a <script></script> tag but jQuery is taking out off from the response. Is there any way to get the html code including the javascript code inside the script tags ?

this is the function :

function ocmenu(url) {       
    $.ajax({
        url: url,
        dataType:"text"
     }).done(function(resp) {
          $('.new').html($('#lay_body_get',resp));
     });
}

2 Answers 2

7

Don't use dataType:"text". Use "html" or leave it on auto.

See: jQuery .ajax docs

"html": Returns HTML as plain text; included script tags are evaluated when inserted in the DOM. "text": A plain text string.

Further down on the same page:

If html is specified, any embedded JavaScript inside the retrieved data is executed before the HTML is returned as a string.

Some other potential causes:

  • The mimeType returned by the server isn't text/html

A simple working example

file1.html

<html>
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>
    <div id="putResultHere">
    </div>

    <script>
        $(function() {
           $.ajax({
                url: 'file2.html',
                dataType:"html"
             }).done(function(resp) {
                  $('#putResultHere').html($(resp));
             });

        });
    </script>
</body>
</html>

file2.html

<h1>Ajax done!</h1>

<script>
alert('script worked');
</script>
Sign up to request clarification or add additional context in comments.

4 Comments

It did not help. May be it help: If I use $('.new').html(resp); scripts dont copy, but they work on page.
Yes, its work, but I need clear code from header and footer and display only body
In that case, my answer is wrong. I accidentally left in dataType: "text" and it still works.
actually, you still get the script inside the div tags - which is an issue for me because my "script" is html (an angular template) and it doesn't work inside the div
0
$(resp).find('script').each(function(i,script){
    eval($(script).text());
});

Make sure you trust the external file..

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.