ajax - jsonp - кросс-доменные запросы
Столкнувшись с проблемой:
Cross-Origin Request Blocked: The Same Origin Policy
disallows reading the remote resource at
http://127.0.0.1:8000/snippets/40. This can be
fixed by moving the resource to the same domain or enabling CORS.
Прогуглил и решил использовать jsonp, что бы обойти это. Изменил json на jsonp. К урлу добавил '?callback=?', в итоге ошибка:
NetworkError: 404 NOT FOUND -
http://127.0.0.1:8000/snippets/40?
callback=jQuery1112027875676172209374_1428411637023&_=1428411637024
Мой код:
function fantasy(){
start(categor='http://127.0.0.1:8000/snippets/', 1, 40);
}
function start(categor, ot, te) {
var start = Math.floor((Math.random() * ot) + te);
jQuery.ajax({
type: 'GET',
url: categor+start+'?callback=?',
dataType: 'jsonp',
jsonp: 'callback',
success: function (data) {
if (data.pk == start) {
document.getElementById('result').innerHTML = data.title;
document.getElementById('image').innerHTML = '<img class="img-responsive" src="img/poetry/'+data.img+'"/>';
document.getElementById('description').innerHTML = '<h4>Описание:</h4>'+data.content;
document.getElementById('author').innerHTML = '<span>Автор: </span>'+data.author;
}
}
});
}
Что я сделал не так?
Решение: спасибо всем, в какой-то мере все варианты решают проблему, именно в моем случае, т. к. сервер написан на Django, то помогла библиотека - django-cors-headers - https://github.com/ottoyiu/django-cors-headers/ + изменение в settings.py CORS_ORIGIN_ALLOW_ALL = True