Reputation: 49
In my projects I work with the MVC api. I am trying to obtain this (and other) data with a full url via AJAX in: url: http://urlexample.com
This give an error: cross origin request blocked
what am I doing wrong? and who can help me? There is a lot to read about this problem, but so far nosolution yet for me.
This is my code:
<script type="text/javascript">
function loadstudentid() {
$.ajax({
// url: '/api/AZstudent', // > work fine
// url: 'http://<domain>.<subdomain>/api/azstudent', > // Gives te issue
cache: false,
dataType: 'json',
success: function (data) {
$(data).each(function (i, item) {
$(item).each(function (i, stud) {
console.log(stud.id_student);
});
});
},
error: function (request, status, error) {
console.log('error', error);
}
});
}
Wy is this working??
<script type="text/javascript">
function doewat() {
var flickerAPI = "http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?";
$.getJSON( flickerAPI, {
tags: "mount rainier",
tagmode: "any",
format: "json"
})
.done(function( data ) {
$.each( data.items, function( i, item ) {
$( "<img>" ).attr( "src", item.media.m ).appendTo( "#images" );
if ( i === 3 ) {
return false;
}
});
});
}
//)();
http://api.jquery.com/jquery.getjson/
tried the following
jQuery.support.cors = false;
and
crossDomain: true,
and:
var url = 'http://myurl.com/api'
Upvotes: 0
Views: 467
Reputation: 5534
The only way to accomplish this is through CORS. You can find a good tutorial on how to achieve it here.
In short, this is (mostly) about the server, not your JavaScript code. You need to make the server set the Access-Control-Allow-Origin to the URL from which you are making your request. If you don't have access to the server, then you're out of luck - the only thing you could do is make your own server (on the same domain) act as a proxy, request from the other server and then pass you the result.
Upvotes: 0
Reputation: 2425
The reason this works:
url: '/api/AZstudent',
is because that is a relative path, meaning it will resolve to its current domain (perhaps localhost?)
The reason the other isn't, is due to the fact the ajax request is originating from domain example.com to > somethingelse.com
This will not work as this will allow people to perform malicious actions.
Here's a more in-depth read on this: https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy
Upvotes: 1