简体   繁体   English

使用 AJAX 在同一页面上将 Javascript var 传递给 PHP

[英]Using AJAX to pass Javascript var to PHP on same page

I have a page that started with an empty PHP var.我有一个以空的 PHP 变量开头的页面。 Then, when the user clicks on a link I want to pass the value of the name attribute to a JS var, and then pass that JS var to the same page and then update the PHP var with the JS var value.然后,当用户单击链接时,我想将 name 属性的值传递给 JS var,然后将该 JS var 传递到同一页面,然后使用 JS var 值更新 PHP var。 Here is a simple example of what I am trying to do:这是我正在尝试做的一个简单示例:

// 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>

A lot of people say that I don't need AJAX for this.很多人说我不需要AJAX。 The example I provided is a much similar version of what I am trying to do, which is dynamically change an include file based on the user clicking a sidebar item.我提供的示例与我正在尝试执行的操作非常相似,它根据用户单击侧边栏项目动态更改包含文件。 I don't want to use a form for this, do I?我不想为此使用表格,是吗?

Ah!啊! As I continued to look, I found that jQuery has the .load() function which is EXACTLY what I wanted.当我继续查看时,我发现 jQuery 具有 .load() 函数,这正是我想要的。 Dang!当! I was able to build this and make it work:我能够构建它并使其工作:

// 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);

So easy.太简单。 Dang.党。 Thanks all.谢谢大家。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM