Reputation: 2777
I am having a webserver running on my localhost. If i load my webpage from my webserver everything works fine. I am able to OPEN a REST session with my webserver.
JS code :--
$(document).ready(function() {
var xhr = new XMLHttpRequest();
var open_str = "http://localhost:8080/vscp/rest?user=admin&password=d50c3180375c27927c22e42a379c3f67&format=json&op=1";
xhr.open("GET", open_str, true);
xhr.onreadystatechange = function() {
alert(xhr.readyState + "" + xhr.status);
if (xhr.readyState == 4 && xhr.status == 200) {
alert("session opend success");
var json = JSON.parse(xhr.responseText);
alert(JSON.stringify(json, null, 10));
}
}
xhr.send();
});
HTML code :--
<!DOCTYPE html>
<html>
<head>
<title>Hello jQuery</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="hello.js"></script>
</head>
<body>
<div>
<p class="greeting-id">Trying to open the REST session with vscpd </p>
</div>
</body>
</html>
Now if i load the same html page from my D: drive :--
file:///D:my_folder/htm_test.html
I am getting following error "No 'Access-Control-Allow-Origin' header is present". And i have checked in javascript code that xhr.readyState is 4 and xhr.status is 0.
Please suggest what changes to make to my javascript code so that, if i open the html file directly from my D: drive using file:///
then also REST session is opened correctly with my webserver.
========================= JSONP code ========================
$(document).ready(function() {
var url = "http://localhost:8080/vscp/rest?user=admin&password=d50c3180375c27927c22e42a379c3f67&format=json&op=1";
function jsonpCallback(response) {
alert('success');
}
$.ajax({
url: url,
dataType: 'jsonp',
error: function(xhr, status, error) {
alert("error" + " " + error.message);
},
success: jsonpCallback
});
return false;
});
Error i get :-- server is sending the right response :-- {"success":true,"code":1,"message":"success","description":"Success","session-id":"e5a36e14b687c37b615dbc6a9506df5c","nEvents":0}
But ajax call giving error for this response i.e "Uncaught SyntaxError: Unexpected token :"
Upvotes: 1
Views: 6432
Reputation: 20264
You have run into the Same Origin Policy - this is a security mechanism that restricts JavaScript loaded from one domain from sending requests to a different domain.
There are various ways around it, if you are using Google Chrome I would suggest setting the --allow-file-access-from-files flag when you start the browser, Firefox also provides a way to work around it, but don't forget to disable these options when you have finished testing, they are there for a good reason!
Upvotes: 4
Reputation: 1
That's because Chrome and some other browsers are blocking the local files for security reasons and I don't think there is a method for resolving this issue. You have to use a webserver.
Upvotes: 0