![](/img/trans.png)
[英]What is the proper syntax to call a global variable function from within a class?
[英]what is the proper syntax for including a variable in this javascript code?
我所依依的那条线是
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;";
请记住,您只是向客户端发送数据,以便稍后运行(或不运行)。 您永远无法将数据从浏览器“拉回”到仍在运行的脚本中。 到浏览器获取数据时,脚本已完成运行,服务器已移至其他有用的功能,例如枚举数据库。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.