【发布时间】:2020-07-31 13:22:21
【问题描述】:
所以基本上我想以这样一种方式设计我的页面,当用户发表评论时,页面不会刷新,但评论会被发送并插入到数据库中。
因此,我需要将评论本身发送到服务器,并且我已经读过最好的方法是使用 JavaScript FormData。问题是我无法让它实际发送一些东西,我希望它将 type="input" 元素中写入的数据发送到服务器。 我之前通过使用 HTML 表单元素本身提供的默认方式来做到这一点:action=link method="post"。
所以我想将广告系列的 id 附加到 url,并尽可能使用 $_POST 和 JavaScript DataForm 将评论本身发送到服务器,这样它就知道应该有该评论的广告系列。
我可以有多个广告系列,它们都将“动态”生成,可以说,使用 PHP 和 JavaScript 脚本来处理它们的行为,所以这就是我回应所有这些的原因。
<form id="commentForm' . $row['id'] . '" name="commentForm" method="post" class="greyContainerAllCampaigns">
<input id="comment' . $row['id'] . '" name="CommentContent" max="250" title="max 250 alphanumeric and ,.?: etc chars" required pattern='.' \'[A-Za-z0-9 .,!?:\[\]()"-+]+\' ' .'class="inputBox" type="text" placeholder="write here">
<button id="commentB' . $row['id'] . '" class="submitButton" type="submit" name="Comment">Comment</button></form>';
这是我尝试编写的 JavaScript 脚本:
document.getElementById("commentB' . $row['id'] . '").addEventListener("click", commentFunction);
function commentFunction() {
fetch(\'http://localhost:80/proiect/GaSM/public/Campaign/comment/'. $row['id'] . '\', {
method: \'POST\',
body : new FormData(document.getElementById("commentForm' . $row['id'] . '")),
headers: {\'Content-Type\':\'multipart/form-data\'}
});
alert ("You left a comment!");
}
</script>';
我尝试使用 $_POST['CommentContent'] 在服务器上获取结果,但我什么也没收到,也没有发送任何内容。
我尝试通过 POST 将其发送到 JavaScript 脚本中的服务器的方式显然做错了,但我不知道是什么。 提前致谢!
【问题讨论】:
标签: javascript php forms fetch-api