我有一个以空 PHP 变量开头的页面。然后,当用户单击链接时,我想将 name 属性的值传递给 JS var,然后将该 JS var 传递到同一页面,然后用 JS 更新 PHP var变量值。这是我正在尝试做的一个简单示例:
// PHP
<?php
// Starts empty, then when posted should update
$jsVar = $_POST['jsVar'];
echo $jsVar;
?>
<!-- HTML-->
<!-- Link to click with name vlue to pull-->
<a href="#" name="link">Click Me</a>
<!-- JAVASCRIPT -->
<!-- Import jQuery -->
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script type="text/javascript">
// On link click
$('a').click(function(e){
// Prevent link default behavior
e.preventDefault();
// Store name vale as jsVar
jsVar = $(this).attr("name");
$.ajax({
type: "POST",
// url: "" <--------------- From what I read, if you want to post to the same page you just don't inclue the URL?
data: {jsVar : jsVar}, // <--------- This was also something I found online that supposedly helps pass JS vars to PHP?
success: function(data)
{
alert("success!");
}
});
});
</script>
很多人说我不需要 AJAX。我提供的示例与我正在尝试执行的操作非常相似,它是根据用户单击侧边栏项目动态更改包含文件。我不想为此使用表单,是吗?
最佳答案
啊!当我继续查看时,我发现 jQuery 有 .load() 函数,这正是我想要的。当当!我能够构建这个并使其工作:
// Store clicked page
var currentPage = $(this).attr("name");
// Build filepath
var currentPagePath = "pages/" + currentPage + ".php";
// Find the div I want to change the include for and update it
$("#pageContent").load(currentPagePath);
就这么简单。当当。谢谢大家。
关于javascript - 在同一页面上使用 AJAX 将 Javascript var 传递给 PHP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51003787/