我引用的行是
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>
$(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>");
}
}
});
});
});
好吧。这就是PHP与Javascript交互的方式。简单地说,它几乎没有。PHP 由生成文本的服务器运行。此文本被发送到浏览器,浏览器运行任何Javascript,抓取图像等。值得庆幸的是,由于Javascript是该文本的一部分,我们可以将任何我们想要的数据塞进去,包括任何服务器状态。
因此,要在客户端初始化Javascript变量(var foo
)(例如,当前值$bar
),您需要将数据塞入Javascript变量声明中。您希望客户端看到的内容如下:
var foo = 3; // or whatever else, depending on $bar
因此,为了做到这一点,你需要在正确的时间echo
$foo
的值,并用Javascript语法包围:
echo "var foo = $bar;";
请记住,您只是将数据发送到客户端,以便稍后运行(或不运行)。您永远无法将数据从浏览器"拉"回仍在运行的脚本。当浏览器获取数据时,脚本已完成运行,服务器已转到其他有用的操作,例如枚举数据库。