0

It seems this question has been answered in the past, however, I'm either 1) having a hard time grasping the solutions or 2) not implementing them correctly.

I have a PHP function, that when run, will return results of a database query. Results look similar to this:

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

I can echo this into a page just fine. What I'd like to do is give an end user the option to refresh the link (which can be done by refreshing the page and echoing a new random string returned by the php function) without having to refresh the whole page. I've tried a few different methods, but it seems the function that returns the element is only run when the page reloads - so my URL never changes.

Here is my latest attempt. I figured the url I'm grabbing from the database was only getting set when the paged loaded. I thought setting a function to initialize the url variable would help - no good. It still only works once on page load.

$(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:  ';
};

You can see it live at www.dannychoofan.com.

Any help is appreciated =0)

4

2 回答 2

1

看起来您正在寻找 ajax 风格的调用。

您应该将 dannyChoo() 函数的内容放入与 index.php 文件处于同一级别的名为 articleLinkGenerator.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);
     });
};
于 2012-08-02T01:28:30.630 回答
0

这是因为 PHP 在页面加载之前运行,而 JavaScript 在页面加载之后运行,所以如果没有另一个页面加载,您的变量永远不会改变。

于 2012-08-02T01:12:01.963 回答