我有两个系统helpdesk.ops.something.in
,dev1.ops.something.in
我fetchP.php
在helpdesk.ops中有一个文件,其代码如下所示:
<?php
header('Access-Control-Allow-Origin: *');
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript">
function someFunc(item) {
$.ajax({method:"GET",
url:"http://dev1.ops.something.in/wallet/createurl.php?phone="+item,
success:function(response){
console.log(response);
}
});
};
</script>';
<?php
echo '<div id="callToWallet" class="sample-button" onclick="someFunc(911234567890);"><a href="#"> Click here</a></div>';
它正在createurl.php
对dev1.ops中存在的文件执行GET请求,如下所示:
<?php
header('Access-Control-Allow-Origin: *');?>
<script>response.addHeader("Access-Control-Allow-Origin", "*");</script>
<?php
// the rest of the code
?>
但是执行时,GET请求未成功,并且出现错误:
XMLHttpRequest cannot load http://dev1.ops.something.in/wallet/createurl.php?phone=911234567890. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://helpdesk.ops.something.in' is therefore not allowed access. The response had HTTP status code 500.
我想念什么?
即使Access-Control-Allow-Origin
设置了标头,XMLHttpRequest也无法在与您当前域不同的域上请求资源(这是由于同源策略)。
您可以尝试解决它的一种方法是使用JSONP。这是一个简单而基本的示例:
fetchP.php
(Ajax调用):
function someFunc(item) {
$.ajax({
method: "GET",
data: { phone: item },
url: "http://localhost:2512/createurl.php",
success: function(response){
console.log(response);
},
dataType: "jsonp",
});
};
createurl.php
:
<?php
header('Access-Control-Allow-Origin: *');
$data = ["foo" => "bar", "bar" => "baz"];
$json = json_encode($data);
$functionName = $_GET['callback'];
echo "$functionName($json);";
?>
createurl.php
ajax请求的示例输出:
jQuery2130388456100365147_1447744407137({"foo":"bar","bar":"baz"});
jQuery然后执行定义的函数,并success
在给定参数(在本例中为JSON)上调用定义的方法。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句