简体   繁体   中英

create javascript file for use on different servers

I want to create a JS file that others can include on their websites so they can reference the functions which access my db using an api similar to the facebook like button which shows the total liked and who of your friends like the page. What I've been doing as part of my testing is the following: JS file

function getItemRating(id){
    var result = "";
    $.ajax({
        type: "POST",
        url: "http://siteurl.com/api/rating.php",
        data: {i : id},
        dataType: "json",
        async: false,
        success: function(data) { // callback for successful completion
          result = data;
        },
        error: function() { // callback if there's an error
          result = 'error';
        }
      });
    return result;
}

Reference file includes:

header("Access-Control-Allow-Origin: *");

and on the other server I've tried a few ways including:

    <!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <script src="//code.jquery.com/jquery-1.11.1.min.js"></script>

<script type="text/javascript" src="www.siteurl.com/api/rating-file.js"></script>
<script type="text/javascript">
    $(document).ready(function(){
    var result = getItemRating(1);
    console.log(result);


});
</script>
</head>
<body></body>
</html>

But currently I'm getting the error in console:

VM133:1 Access to XMLHttpRequest at ' http://siteurl.com/api/rating.php ' from origin ' http://otherurl.com ' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

siteurl.com = my server where the js file (with function) is located otherurl.com = different server that the html including the js is located

The error message tells you that the problem is with the response to the preflight request, but you shouldn't be triggering one in the first place.

Remove:

contentType: "application/json; charset=utf-8",

because:

  • It is a lie. You aren't POSTing JSON in your GET request.
  • Setting the content-type to that value triggers a preflight request.

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