问题
I am having a problem requesting a random number from random.org using jQuery. When I'm using a static page and the following javascript, I don't have any issues getting random numbers. However, I am hosting a Sinatra app on Heroku (also, when running my app locally in production using Thin) I get "(website) is not allowed by Access-Control-Allow-Origin."
function raffler(){
var rowCount = $('#winnerTable tr').length;
$('#winnerButton').click(function() {
$.get("http://www.random.org/integers/?", {num: "1", min: "1", max: rowCount, col: "1", base: "10", format: "plain", rnd: "new"}, function(randNum) {
var myNumber = randNum;
$("#entry-" + randNum).addClass('winner');
});
});
};
Thoughts?
回答1:
Honestly I don't get how you could do that in any way. Because you shouldn't be able to do it. Access-Control-Allow-Origin is an XSS protection which blocks cross domain requests and is part of most client side scripting engines (e.g. Flash). Use the following to random number generation:
Math.random()
回答2:
Well, on a quick check, random.org doesn't return any CORS headers. This explains, why you are not allowed to request it via Javascript from your website.
Hav you loaded your static file, where it works, locally, i.e., via file:///
protocol? There are other security measurements on duty, and browsers usually allow cross-domain AJAX.
回答3:
Use jQuery YQL plugin to get result from this page.
It bypasses origin check by using Yahoo service to get content of needed page.
http://plugins.jquery.com/project/jquery-yql-plugin
But it is very complicated way. Why don't you use Math.random() ?
来源:https://stackoverflow.com/questions/7031191/jquery-and-random-org-is-not-allowed-by-access-control-allow-origin