我有一个以空PHP var开头的页面。然后,当用户单击一个链接时,我希望将name属性的值传递给JS var,然后将该JS var传递给同一页面,然后使用JS var值更新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来做这件事。我提供的示例与我正在尝试做的事情非常相似,即根据用户单击侧栏项目来动态更改包含文件。我不想为此使用表单,对吧?
发布于 2018-06-24 02:25:55
阿!当我继续查看时,我发现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);
这么简单。见鬼。谢谢大家。
https://stackoverflow.com/questions/51003787
复制相似问题