【问题标题】:How do I use Ajax to auto refresh a div across domains?如何使用 Ajax 跨域自动刷新 div?
【发布时间】:2013-05-31 14:13:26
【问题描述】:

有人可以帮帮我吗?我有一个 html 文件,它通过 ajax 调用 php 脚本并显示 php 脚本生成的随机数。当两个文件都在同一个域上时它工作得很好,但是如果这两个文件位于不同的域中,这是我需要的,什么都不会发生。谁能帮我解决这个问题。

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 请求包装器的文档,但我不知道它的去向。任何帮助将不胜感激。

【问题讨论】:

    标签: php ajax json refresh


    【解决方案1】:

    你不能使用 ajax 跨域这是不可能的,但你有以下选择:

    1.对您自己的页面执行 ajax 并对该页面进行 curl 调用..

    2.do $.getJSON('ur', variables, function(data){}).

    几乎没有其他解决方案,但这两个基本上是您的最佳选择

    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.
    });
    

    【讨论】:

    • 您能否提供一个示例,使用我的代码作为起点,使用 jetJSON。我会很感激的。
    • 好吧,使用 getjson,您需要在“服务器”或您需要访问的任何跨域地址上创建一个页面,该页面接受 get 调用,并重新运行一个函数..会给你一个很快的例子。
    • 好吧,我为你解决了我的答案。不要忘记回调必须是你从 php 返回的变量的包装器。
    猜你喜欢
    • 2015-01-21
    • 2014-04-23
    • 2013-09-01
    • 1970-01-01
    • 2023-04-03
    • 2013-03-11
    • 2010-10-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多