简体   繁体   中英

Jquery ajax not working - No 'Access-Control-Allow-Origin'

<html>
    <head>
        <title></title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$( document ).ready(function() {

$('#my-form')
  .submit( function( e ) {
    $.ajax( {
      url: 'http://111.111.111.111:5008/form',
      type: 'POST',
      data: new FormData( this ),
      processData: false,
      contentType: false,
      success: function (data) {
       alert("SUCCESS");
      },
      error: function (textStatus, errorThrown) {
       alert("FAILED");
    }
  } );
    e.preventDefault();
  } )


});
</script>   
    </head>
    <body>
        <div>
            <form id="my-form">
                    <div>
                        File:
                            <input type="file" name="file" />
                    </div>
                    <div>
                        <button type="submit">Submit</button>
                    </div>
            </form>
        </div>
    </body>
</html>

I need to submit a form and see if it was successful. The file is being uploaded on my server side and there are no errors, but ajax is saying it is failing (Failed alert showing). I opened the console and it gives the error:

XMLHttpRequest cannot load http://111.111.111.111:5008/form. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://111.111.111.111' is therefore not allowed access.

So the form is being uploaded because I can see it is from my database. I googled the error and it seems I can use jsonp as a datatype in my ajax. I tried this and it did not work, but I would rather not use this for the security risks and I have no need for that data type.

I have found the issue. From my server the response back needs to modify the header. The header needs to allow all origins. Here is an example with Java (vertx.io).

ctx.response().putHeader("Access-Control-Allow-Origin ", "*");

Once I added this to my server code, the requests and responses work as needed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM