[英]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. 我想创建一个JS文件,其他人可以在他们的网站上包括这些文件,以便他们可以使用类似于facebook like like按钮的API来引用访问我的数据库的功能,该按钮显示喜欢的总人数以及喜欢该页面的朋友们。 What I've been doing as part of my testing is the following: JS file 作为测试的一部分,我一直在做以下工作:JS文件
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. VM133:1从源' http://otherurl.com '对' http://siteurl.com/api/rating.php '处的XMLHttpRequest的访问已被CORS策略阻止:对预检请求的响应未通过访问控制检查:所请求的资源上没有“ Access-Control-Allow-Origin”标头。
siteurl.com = my server where the js file (with function) is located otherurl.com = different server that the html including the js is located siteurl.com =我的js文件(带有功能)所在的服务器otherurl.com =包含js的html所在的其他服务器
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: 因为:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.