0
$.ajax({
      url: "test.html",
      context: document.body,
      success: function(){
        $(this).addClass("done");
      }
    });

How do I run javascript within test.html and make it work ?

Thanks Abhinab

3
  • It doesn't make much sense the example, but apart from that, use success : function (response), being response the returned html, so that you can manipulate it. Commented Oct 31, 2011 at 1:36
  • 2
    Similar to How to execute javascript inside a script tag returned by an ajax response Commented Oct 31, 2011 at 1:36
  • Are you asking whether it is possible to execute javascript in test.html before it is sent from the server to the browser? If so, the answer is easy. You can't. Commented Oct 31, 2011 at 1:36

2 Answers 2

1

It doesn't really work like that. Javascript in a page is interpreted by the browser when the page is loaded. In this case you aren't loading a page in the browser, you're just getting the page in your ajax response. That response HTML may have <script> elements in them, but nothing is going to do anything with it.

I hesitate to even say this, but you could parse the response in your success function to find all of the script elements, then add whatever you're looking for to your own page's DOM. That should cause the script to be fetched and evaluated. I hesitate to mention it because it smells really bad. If any of my developers did this we'd be having a tough conversation. ;-)

It might help to elaborate on what you're trying to accomplish, as there might be a more elegant way to achieve your goals.

Sign up to request clarification or add additional context in comments.

Comments

0
function call_recursive(){
    var pages ["test1.html", "test2.html", "test3.html" ];

    while(pages.length() > 0){
        page = pages.pop();           
        $.ajax({
            url: page,
            context: document.body,
            success: function(){
                $("div#logger").append("<p>" + page " loded </p>");
            },
            error: function(){
                $("div#logger").append("<p class'error'>" + page " is not loded </p>");
            },
        });
    }
}

just execute call_recursive

2 Comments

Hello, Thanks for the reply .. But I want to execute multiple function in a loop .. as in test.html which actually will be a php file .. includes many more pages ... so after including everypage I want to show on a div ..page 1 loaded ..page 2 loaded I hope I made myself clear. HOpe you can help me up with this :) thanks ABHINAB
you don't need javascript in those ajax pages, just append on ajax success step you accomplished. I'll update my answer in a minute

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.