有人可以帮帮我吗?我有一个html文件,通过ajax调用php脚本,并显示php脚本生成的随机数。当两个文件位于同一个域时,它工作正常,但如果2个文件位于不同的域,这是我需要的,没有任何反应。有人可以帮我解决这个问题。
HTML文件的代码是:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">// <![CDATA[
$(document).ready(function() {
$.ajaxSetup({ cache: false }); // This part addresses an IE bug. without it, IE will only load the first number and will never refresh
setInterval(function() {
$('#divToRefresh').load('http://www.OTHERDOMAIN.com/random.php');
}, 5000); // the "5000" here refers to the time to refresh the div. it is in milliseconds.
});
// ]]></script>
</head>
<body>
<div id="divToRefresh">Loading users...</div>
</body>
</html>
如果该行
$('#divToRefresh').load('http://www.OTHERDOMAIN.com/random.php');
更改为:
$('#divToRefresh').load('random.php');
并放在与html文件相同的文件夹中。一切都很好。
php文件的代码是:
<?php
$random1 = sprintf("%02f", rand(0,9212));
echo $random1;
?>
允许跨域ajax调用的修订代码是什么样的?我正在阅读谈论json请求包装器的文档,但我没有得到它的发展方向。任何帮助都将非常感激。
答案 0 :(得分:0)
您无法使用ajax跨域,但您有以下选择:
1.将ajax发送到您自己的页面并对该页面进行卷曲调用..
2.do $ .getJSON('ur',变量,函数(数据){})。
其他解决方案很少,但这两个基本上是你最好的选择
这是getJson的工作原理:
在你的服务器上,你应该有一个页面可以接收$ _GET类似API或者正常的ajax调用可以用$ _POST。
应该看起来像:
<?php
if(!empty($_GET['jsoncallback']) && !empty($_GET['variable'])){
/* do whatever you like with the variable you get as get
*
*
*
**/
// echo the name of the callback function + the variables you want to receive back in JS
echo $_GET['jsoncallback'].'('.json_encode($jason_echo).')';
}
?>
您要进行调用的JS或页面应该类似于:
$.getJSON("SomePage/PagethatTakesTheGet.php?jsoncallback=?", {variable:15}, function(response){
// do whatever you want with response.
});