将PHP函数的结果加载到DIV容器中


Loading results of PHP function into DIV container

这个问题在过去似乎已经得到了回答,然而,我要么1)很难掌握解决方案,要么2)没有正确实现它们。

我有一个PHP函数,当运行时,它将返回数据库查询的结果。结果与此类似:

<a href="http://www.dannychoo.com/post/en/26468/Koenji.html" class="danny-choo">Koenji</a>

我可以把它回声到一个页面上。我想做的是让最终用户可以选择刷新链接(可以通过刷新页面并回显php函数返回的新随机字符串来完成),而不必刷新整个页面。我尝试了几种不同的方法,但返回元素的函数似乎只有在页面重新加载时才运行,所以我的URL永远不会改变。

这是我最近的一次尝试。我想我从数据库中获取的url是在加载页面时才设置的。我认为设置一个函数来初始化url变量会有所帮助——没有好处。它仍然只在页面加载时工作一次。

$(document).ready(function() {
    updateVariable();
    $('#dannychoolink').html(random + url);
    $('.danny-choo').attr('target', '_blank');
});
$('#clicky').click(function() {
    updateVariable();
    $('#dannychoolink').html(random + url);
    $('.danny-choo').attr('target', '_blank');
});
function updateVariable() {
    url = '<?php echo dannyChoo();?>';
    random = 'Random DannyChoo.com article:  ';
};

你可以在www.dannychoofan.com上看到它的直播。

感谢任何帮助=0)

看起来像是在寻找ajax风格的调用。

您应该将dannyChoo()函数的内容放入一个名为articleLinkGenerator.php的新文件中,该文件与index.php文件处于同一级别。这个文件应该包含dannyChoo()函数的内容,这样它就可以自动执行并回声你期望的链接(如)的html

<?php
    function dannyChoo(){
        // generate random link code
        echo $random_link_html // Like <a href="http://www.dannychoo.com/post/en/26468/Koenji.html" class="danny-choo">Koenji</a>
     }
      dannyChoo();

然后在index.php(主网站)中使用ajax更新您的函数(http://api.jquery.com/jQuery.get/)看起来像:

$(document).ready(function() {
    updateVariable();
});
$('#clicky').click(function() {
    updateVariable();
});
function updateVariable() {
    $.get('articleLinkGenerator.php',function(data){
        $('#dannychoolink').html(data);
     });
};

这是因为PHP在页面加载之前运行,JavaScript在页面加载之后运行,所以在没有其他页面加载的情况下,您的变量永远不会更改。