2

Is it possible to change this code, so it will work recursively if the http://www.myurl.com redirect to the js file that should run?

function include(scriptUrl)
{
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.open("GET", scriptUrl);
        xmlhttp.onreadystatechange = function()
        {
            if ((xmlhttp.status == 200) && (xmlhttp.readyState == 4))
            {
                eval(xmlhttp.responseText);
            }
        };
        xmlhttp.send();
}
include("http://www.myurl.com");
Gorden Gram
  • 921
  • 2
  • 10
  • 14

2 Answers2

2

Why not just do:

$("head").append("<script src='http://myurl.com' type='text/javascript'></script>"); 

Of course you can do it without jquery but that's the jist of it. If you're just pulling from a URL that only requires GET arguments (if any at all) then it's easier (and safer) to just add a new script element that includes it.

This will also take care of your redirection issue since the browser will follow the redirect.

PhonicUK
  • 13,486
  • 4
  • 43
  • 62
1

When the URL redirects you to another location it will probably give you a 301 status instead of a 200 status. In that case your check should be:

if ((xmlhttp.status == 200 || xmlhttp.status == 301) && xmlhttp.readyState == 4)

Or you can choose to allow all but the error statuses:

if (xmlhttp.status < 400 && xmlhttp.readyState == 4)
Jasper de Vries
  • 19,370
  • 6
  • 64
  • 102
  • It doesn't eval the js when adding this statuses. I tried to add 'else if' for status 301 and then calling include with the new url but after its eval the script (let's say the script is: alert("hello");) its continue to call it again with "www.example.com/alert("hello); for some reason.. any suggests? – Gorden Gram Aug 29 '12 at 12:34
  • Can you do a `console.log` of `xmlhttp`? Is the status as expected? Do you get a `responseText`? – Jasper de Vries Aug 29 '12 at 12:39
  • well I don't know why but after including this 'else if' and writing it: ((xmlhttp.status == 301) && (xmlhttp.readyState == 4)) - checking that the state is 4 its working! it didn't work before but who remember what I wrote before :) – Gorden Gram Aug 29 '12 at 13:04