Ajax request for another host

There is the following javascript on my web page:

var xhr = new XMLHttpRequest(); xhr.open('GET', 'http://www.google.com', true); xhr.onreadystatechange = function() { if (xhr.readyState == 4) { alert('resp received, status:' + xhr.status + ', responseText: ' + xhr.responseText); } }; xhr.send(null); 

runs and ends w / readyState of 4, state 0 and empty responseText and responseXML. I know that it really sends a b / c request, which I tried to send xhr to the server on my machine, and the server really responds. why am I not getting anything in responseText? is there something to do with the fact that xhr is going to another server?

when I open the js debugger and type 'xhr' to check the object, I get the following:

XMLHttpRequest
DONE: 4
HEADERS_RECEIVED: 2
DOWNLOAD: 3
OPEN: 1
MESSAGE: 0
abort: function abort () {
addEventListener: function addEventListener () {
dispatchEvent: function dispatchEvent () {
getAllResponseHeaders: function getAllResponseHeaders () {
getResponseHeader: getResponseHeader () function {
onabort: null
onerror: null
onload: null
onloadstart: null
onprogress: null
onreadystatechange: function () {
open: open () function {
overrideMimeType: function overrideMimeType () {
readyState: 4
removeEventListener: removeEventListener () function {
responseText: "
responseXML: null
send: send () function {
setRequestHeader: function setRequestHeader () {
status: 0
statusText: ""
download: XMLHttpRequestUpload
withCredentials: false

+1
javascript ajax
source share
4 answers

is there anything to do with the fact that xhr is going to a different server?

Yes, you cannot send requests to other servers through AJAX. Whereas, you can send your requests from the server side. Thus, you need to implement the following workflow: Your page โ†’ Your server โ†’ Third-party server โ†’ Your server โ†’ Your page, where "->" means sending data.

+15
source share

Crossite scripting is a common way to enter code on someone elseโ€™s web page. To limit this, most browsers no longer allow the client-side developer to create a JavaScript request (usually via XMLHttpRequest ) to web pages located in a different domain to the source page.

You can get around this simply by creating a dummy script in your domain that sends the same request to the page you need. For example, in your case, you should create a request at http://mydomain.com/google.php (or whatever scripting language you prefer) that will then load a Google page using file_get_contents or similarly and simply echo .

+2
source share

You cannot perform cross-domain requests using javascript. It is best to use the server as a proxy.

+1
source share

YOU CAN execute cross-domain requests if the server is configured to allow it: see How does the Access-Control-Allow-Origin header work? and google about Access- The header is Control-Allow-Origin.

+1
source share

All Articles