Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
485 views
in Technique[技术] by (71.8m points)

jquery - Access-Control-Allow-Origin error

I'm using the following script -

<!DOCTYPE html>
<html>
<head>
<script src="jquery-1.9.1.min.js"></script>
<script>
function postForm() {

    $.ajax({
            type: 'POST',
            url: 'http://10.0.0.8:9000/demo',
            data: {"name" : "test"},
            contentType: "application/json; charset=utf-8",
            dataType: 'json',
        })
    }

</script>
</head>
<body>
    <form id="ajaxForm" onsubmit="postForm(); return false; "  method="post"> 
        <input id="test" type="text" name="name" value="Hello JSON" /> 
        <input type="submit" value="Submit JSON" /> 
    </form>

</body>
</html>

The computer i'm trying to access is running the play framework. I am receiving the following error:

OPTIONS http://10.0.0.8:9000/demo 404 (Not Found) jquery-1.9.1.min.js:5 XMLHttpRequest cannot load http://10.0.0.8:9000/demo. Origin http://localhost:8080 is not allowed by Access-Control-Allow-Origin.

I've been stumped now for two days, can anyone help me out?

Thanks ahead

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The problem is that you're trying to make a cross-origin call (from http://localhost:8080 to http://localhost:9000). That's not allowed by the Same Origin Policy, so the browser is trying to use Cross-Origin Resource Sharing to ask the server if it's okay to allow the cross-origin call. (That's the OPTIONS HTTP request you're seeing.) Since the server doesn't reply to the OPTIONS request with headers allowing the call, it's denied by the browser for security reasons.

The SOP applies to all true "ajax" calls (e.g., ones via XMLHttpRequest). You can either:

  1. Update the server to implement the response to the OPTIONS request passing back the headers to allow the call (which will make it work on most modern browsers), or

  2. Make the request to the same port (I'm guessing there's a reason you're not doing that), so the request is to the same origin and the SOP doesn't apply, or

  3. Switch over to using JSON-P. But JSON-P is inappropriate for form submissions because it's a GET, and GET operations are meant to be idempotent, which most form submissions aren't. So unless this happens to be an idempotent form submission (for instance, a search), using JSON-P would be a hack at best.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...