$.ajax(): Origin null is not allowed
I'm just starting with $.ajax()
. This is my code:
<html>
<head>
<title>Commons app</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
</head>
<body>
<script type='text/javascript'>
if($) console.log('jQuery loaded!\n');
$(function () {
$.ajax({
url: 'http://en.wikipedia.org/w/api.php?action=query&list=allimages&ailimit=5&aifrom=Albert&aiprop=dimensions|mime&format=jsonfm&callback=?'
})
.done(function () { console.log('Yay!'); })
.fail(function () { 开发者_如何学Pythonconsole.log('Error!'); })
.always(function () { console.log('Complete!'); });
});
</script>
</body>
</html>
For some reason I get the following error message:
XMLHttpRequest cannot load http://commons.wikimedia.org/w/api.php?action=query&generator=allimages&gailimit=4&gaifrom=T&prop=imageinfo&iiprop=url&callback=?. Origin null is not allowed by Access-Control-Allow-Origin.
Update: This method is deprecated from jQuery 1.9. Does not work anymore.
Old answer:
Try this (updated):
$.support.cors = true;
$(function () {
$.ajax("http://commons.wikimedia.org/w/api.php?action=query&generator=allimages&gailimit=4&gaifrom=T&prop=imageinfo&iiprop=url&callback=?")
.complete(function () { alert('complete'); })
.error(function () { alert('error'); })
.success(function (data) { alert(data); });
});
More about jQuery.support.cors setting here: jQuery.support
P.S. thanks for a nice question! I believe it will be useful for me also in future.
You need to be aware of the cross-domain-restrictions for AJAX requests, which will prevent you from loading arbitrary websites in the background for safety reasons. See here for more information.
Old Answer:
When you use $(foo)
you need to specify with foo
which elements you mean to modify. What you probably are looking for is something like this:
$(document).ready(function(){
// do something
}
This will execute the functions once the document finished setting up its DOM structure.
精彩评论