[英]JQuery Value to PHP with Ajax?
我的网站上有一个带有随机播放列表和评论列表的视频播放器。
载入所有已写的注释。 现在,我想在每次启动新视频时更改评论ID,以便站点仅显示该视频的评论。
该播放器是使用Javascript设置的,并具有on Ready函数,该函数会触发ajax函数。 注释设置为带有$ value的php行。
这是我的代码:
<div id="comments">
<?php
$commentsID= 3; //Testnumber 3 shows all comments to video 3
Comment::getCommentSystem($commentsID);
?>
</div>
<script>
onReady: function(event) {
videoID; // actual videoID
//and here comes some Ajax Magic, to tell $commentsID = videoID, but how?
// My example doesn't work because it's my first try with Ajax whoohooo
$.ajax({
type: "GET",
url: "index.php",
data: videoID,
success: function(videoID){
$('#comments').empty(); // Clear Testnumber'n stuff
$(' <?php
$commentsID= videoID;
Comment::getCommentSystem($commentsID);
?>
').appendTo('#comments'); // rewrite the comments Div with the videoID
}
});
</script>
编辑:
现在我的代码如下:
<div id="comments">
</div>
<script>
[...]
onReady: function(event) {
videoID; // actual videoID
$.ajax({
type: "GET",
url: "get_comments.php?videoId=" + videoID,
success: function(response){
$('#comments').html(response);
}
});
}
[...]
</script>
get_comments.php
<?php
session_start();
include "comment.class.php";
$videoID = $_GET["videoId"];
$comments = Comment::getCommentSystem($videoID);
return($comments);
?>
它产生了这个:
<div id="comments">
<!-- The Form to add a comment ( always display none ) -->
<div style="display:none;">
<div class="comment-post comment-child">
<form id="addCommentForm" action="" method="post">
<!-- The Form container, that shows the Form comment -->
<!-- ( should be visible - maybe session fail? ) -->
<div class="comment-container" style="display:none;">
<div class="comment-content">
<!-- all comments to videoID 3 -->
<ul class="comment-list-3">
</div>
不要将其发送给index.php,而是将请求发送到另一个端点,例如get_comments.php
,
<script>
onReady: function(event) {
videoID; // actual videoID
//and here comes some Ajax Magic, to tell $commentsID = videoID, but how?
// My example doesn't work because it's my first try with Ajax whoohooo
$.ajax({
type: "GET",
url: "get_comments.php?videoId=" + videoID,
success: function(response){
$('.comment-list-3').empty(); // Clear Testnumber'n stuff
var html = '';
$.each(response, function(i, item) {
// Do your html here. I assume, your comment object has a field "text". Update it according too your need
html += '<div>' + item.text + '</div>';
});
$('.comment-list-3').html(html); // rewrite the comments Div with the videoID
}
});
</script>
并在您的get_comments.php
;
<?php
$videoID = $_GET["videoId"];
$comments = Comment::getCommentSystem($videoID); // Let say this is array
echo json_encode($comments);
?>
正如HüseyinBABAL所述,您可以使用$ _GET接收视频ID,然后准备页面。 Yuou可以将$ _GET值存储在属性中(例如:data-video-id =“ 3”),以便您可以使用JS / jQUery读取它。 可以使用JS来获取URL部分,但这要困难一些。
警告:如果您使用用户输入(例如$ _GET和$ _POST),请始终验证输入。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.