0

我指的是

url:"../php/loadmorecommentsuserpage.php?profilepageuserid=$profilepageuserid&lastComment="+$(".postedComment:last").attr("id"),

我想通过 GET 将 $profilepageuserid 发送到 loadmorecommentsuserpage.php,但它不起作用。

特别是 $profilepageuserid 代表的值没有被发送。那么语法错误吗?

$profilepageuserid 是 PHP 中的一个变量,我想通过 JS 发送它

<script>
    $(document).ready(function(){
        $('div#text').click(function(){
            $("div#text").hide();
            $('div#loadMoreComments').show();
            $.ajax({
                url:"../php/loadmorecommentsuserpage.php?profilepageuserid=$profilepageuserid&lastComment="+$(".postedComment:last").attr("id"),
                success:function(html){
                    if(html){
                        $("#postedComments").append(html);
                        $('div#loadMoreComments').hide();
                        $('div#text').show();
                    }else{
                        $('div#box').replaceWith("<div class='box'><center>Finished Loading the Comments</center></div>");
                    }
                }
            });
        });
    });
</script>
4

2 回答 2

3
$(function() {

    //your variable
    //if it's from PHP, you need to echo it to a JS variable
    var profilepageuserid = '<?= $profilepageuserid ?>'

    $('div#text').on('click',function() {

        //store required data into variables
        //keeps your code readable
        var commentid = $(".postedComment:last").attr("id");

        $(this).hide();
        $('div#loadMoreComments').show();

        $.ajax({
            url:"../php/loadmorecommentsuserpage.php",

            //instead of a very long querystring, just do "data"
            data : {
                'profilepageuserid' : profilepageuserid,
                'lastComment' : commentid
            },
            success: function(html) {
                if (html) {
                    $("#postedComments").append(html);
                    $('div#loadMoreComments').hide();
                    $('div#text').show();
                } else {
                    $('div#box').replaceWith("<div class='box'><center>Finished Loading the Comments</center></div>");
                }
            }
        });
    });

});​
于 2012-04-13T07:35:57.223 回答
1

好吧。这就是 PHP 与 Javascript 交互的方式。简单地说,它几乎没有。PHP 由生成文本的服务器运行。该文本被发送到浏览器,该浏览器运行任何 Javascript、抓取图像等。幸运的是,由于 Javascript 是该文本的一部分,我们可以将任何我们想要的数据塞入其中,包括任何服务器状态。

因此,要在客户端初始化一个 Javascript 变量 ( var foo)(比如 的当前值$bar),您需要将该数据填充到一个 Javascript 变量声明中。您希望客户看到的内容如下:

var foo = 3; // or whatever else, depending on $bar

因此,为了做到这一点,您需要在正确的时间使用 Javascript 语法包围的echo值:$foo

echo "var foo = $bar;";

请记住,您只是向客户端发送数据,以便稍后运行(或不运行)。您永远不能将数据从浏览器“拉”回仍在运行的脚本中。当浏览器获取数据时,脚本已经完成运行,服务器已经开始处理其他有用的事情,例如枚举数据库。

于 2012-04-13T07:42:37.673 回答