我有两个系统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>';
Run Code Online (Sandbox Code Playgroud)
这是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
?>
Run Code Online (Sandbox Code Playgroud)
但在执行时,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.
我错过了什么?
Pad*_*rom 12
即使使用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",
});
};
Run Code Online (Sandbox Code Playgroud)
createurl.php:
<?php
header('Access-Control-Allow-Origin: *');
$data = ["foo" => "bar", "bar" => "baz"];
$json = json_encode($data);
$functionName = $_GET['callback'];
echo "$functionName($json);";
?>
Run Code Online (Sandbox Code Playgroud)
createurl.phpajax请求的输出示例:
jQuery2130388456100365147_1447744407137({"foo":"bar","bar":"baz"});
Run Code Online (Sandbox Code Playgroud)
然后jQuery执行定义的函数并success在给定的参数上调用已定义的方法(在本例中为JSON).
| 归档时间: |
|
| 查看次数: |
20043 次 |
| 最近记录: |