0

I want to catch cross domain response in pure javascript ajax not using jquery or other external libraries.

var xmlhttp, response;

try {
    xmlhttp = new XMLHttpRequest(); 
} catch(e) { 

   try { 
        xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e2) { 

       try {
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (e) {}
    }
}

xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState==4) { 
        if(callback != undefined) { 
              console.log(xmlhttp.responseText);
        }
    }
}

url = "http://xxxx.com/layer.php?callback=callRes";
xmlhttp.open("GET", url, false);
xmlhttp.setRequestHeader("Content-Type",
                    "application/json,application/javascript,text/javascript");
xmlhttp.send();

spent lots of time and googling but not find any solution

suggestions are most welcome but not script method only pure javascript ajax

7
  • 1
    Should not be possible. The Same Origin Policy can only be avoided by the use of some Browser Plugins. Why not JSONP? Commented Jul 31, 2014 at 13:37
  • It would have to be JSONP. Commented Jul 31, 2014 at 13:38
  • as i mentioned in my question i want to use pure javascript ajax not script method Commented Jul 31, 2014 at 13:45
  • Where is the response coming from? Do you have access to adjust the headers? If so use CORS and adjust the headers to allow your front end code access. This can even be accomplished on S3 if the resource you're requesting is on there. Commented Jul 31, 2014 at 13:52
  • Do you have access to this file xxxx.com/layer.php ? Commented Jul 31, 2014 at 13:52

1 Answer 1

0

I assume you want to see the response in console.

Before calling console.log() you are checking to see if callback exists. In the given piece of code callback is not yet defined so maybe this is the only barrier preventing the output of xmlhttp.responseText.

Solution: remove if (callback != undefined) and just call console.log(xmlhttp.responseText)

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

3 Comments

i'm trying this but unfortunately it not working
You get some error message? Add console.log(xmlhttp.readyState) at the beginning of the onreadystatechange function to see how far it goes.
getting response in network window but not catch

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.