Search code examples
javascriptxmlhttprequestcross-domainresponse

XMLHttpRequest cross domain


i have this javascript code for extract text from page, it works fine if i open file in my domain, but i cant get text from file in another domain, because some security reasons. So my question is how can i please extract text from another website in javascript, please without jquery.

Thank you

function reqListener () {
  console.log(this.responseText);
}

var xhr = new XMLHttpRequest();

xhr.onload = reqListener;

xhr.onreadystatechange = function() {
    if (xhr.readyState == 4) {
        alert(xhr.responseText);
    }
}
xhr.open('GET', 'http://anotherweb.com/datafile.php', true);
xhr.setRequestHeader('Content-Type', 'text/plain');
xhr.send(null);

I tried this and it doesnt work.

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">

$(document).ready(function(){
  $("button").click(function(){
    $.ajax({
      url: "http://localhost/index.php",
      dataType : "json",
      contentType: "application/json; charset=utf-8",
      cache: false,
      success: function(response) {
        alert(response);
      },
      error: function (e) {                
      }
      });
  });
});
</script>
</head>
<body>
<button>Send an HTTP GET request to a page and get the result back</button>
</body>
</html>

Solution

  • If Access-Control-Allow-Origin header is set in response headers of datafile.php it works :)