0

I've confused between this CORS?? :-(

I just ask a little help from you. What is the complete source code for XMLHttpRequest using javascript CORS. How I get json data from a server that sent. If I can access to the json file using address bar. How I get those data from it?

Here Is Json File "Data.json"

{"JsonProjectIDResult": [{"_capacity": 15,"_description": "Meeting Room","_dev_default_view": 3,"_deviceID": 1,"_deviceName": "MobiTech","_deviceTypeID": 1,"_projectID": 1,"_roomID": 2,"_roomName": "Room2","_room_admin_mail": null}]} 

Here My home.html simple script

var resultDiv = document.getElementById("results");
var newsURL = "http://10.1.128.106/JsonDohaBackToTemplate/getProjectIDByMAC.svc/mac/10:95:84:11:00:05";
var e;
if (window.XMLHttpRequest) {
    // code for IE7+, Firefox, Chrome, Opera, Safari
    e = new XMLHttpRequest();
} else {
    // code for IE6, IE5
    e = new ActiveXObject("Microsoft.XMLHTTP");
}
e.onreadystatechange = function() {
    var html = " ";
    if (e.readyState == 4 && e.status == 200) {
        response = JSON.parse(e.responseText);

        if(typeof(e.responseText)==="string") {
            d = e.responseText;
        } else {
            if (typeof(e.responseXML)==="object") {
                d = e.responseXML;
            };
        }
        var myData = response['JsonProjectIDResult'];
        //Loop
        var html = "<ul>";
        var counter = 0;
        for(var prop in myData[counter]) {
            if(myData[counter].hasOwnProperty(prop))
            html += "<li>" + prop + " = " + myData[counter][prop] + "</li>";
        }
        resultDiv.innerHTML = html;
    }
};
e.open("GET", newsURL, true);
e.send();
fab
  • 317
  • 4
  • 20
yeshansachithak
  • 832
  • 2
  • 18
  • 34

1 Answers1

2

Using CORS requires no changes to the JavaScript. It is handled with HTTP headers sent by the server the request is being made to.

i.e. example.com has JavaScript that wants to read from example.net. example.net must use CORS to give permission to example.com to read that data.

At its most basic, example.net needs to include:

Access-Control-Allow-Origin: http://example.com

in the response headers.

More complex situations may require the setting of those headers for a pre-flight OPTIONS request too.

More details can be found at MDN.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335