如何将 JavaScript 变量传递给 PHP?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1917576/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 21:53:09  来源:igfitidea点击:

How do I pass JavaScript variables to PHP?

phpjavascriptvariables

提问by SUN Jiangong

I want to pass JavaScript variables to PHP using a hidden input in a form.

我想使用表单中的隐藏输入将 JavaScript 变量传递给 PHP。

But I can't get the value of $_POST['hidden1']into $salarieid. Is there something wrong?

但我无法获得$_POST['hidden1']into的价值$salarieid。有什么不对?

Here is the code:

这是代码:

<script type="text/javascript">
    // View what the user has chosen
    function func_load3(name) {
        var oForm = document.forms["myform"];
        var oSelectBox = oForm.select3;
        var iChoice = oSelectBox.selectedIndex;
        //alert("You have chosen: " + oSelectBox.options[iChoice].text);
        //document.write(oSelectBox.options[iChoice].text);
        var sa = oSelectBox.options[iChoice].text;
        document.getElementById("hidden1").value = sa;
    }
</script>

<form name="myform" action="<?php echo $_SERVER['$PHP_SELF']; ?>" method="POST">
    <input type="hidden" name="hidden1" id="hidden1" />
</form>

<?php
   $salarieid = $_POST['hidden1'];
   $query = "select * from salarie where salarieid = ".$salarieid;
   echo $query;
   $result = mysql_query($query);
?>

<table>
   Code for displaying the query result.
</table>

采纳答案by Sergey Kuznetsov

You cannot pass variable values from the current page JavaScript code to the current page PHP code... PHP code runs at the server side, and it doesn't know anything about what is going on on the client side.

您不能将变量值从当前页面 JavaScript 代码传递到当前页面 PHP 代码...... PHP 代码运行在服务器端,它对客户端发生的事情一无所知。

You need to pass variables to PHP code from the HTML form using another mechanism, such as submitting the form using the GET or POST methods.

您需要使用另一种机制将变量从 HTML 表单传递给 PHP 代码,例如使用 GET 或 POST 方法提交表单。

<DOCTYPE html>
<html>
  <head>
    <title>My Test Form</title>
  </head>

  <body>
    <form method="POST">
      <p>Please, choose the salary id to proceed result:</p>
      <p>
        <label for="salarieids">SalarieID:</label>
        <?php
          $query = "SELECT * FROM salarie";
          $result = mysql_query($query);
          if ($result) :
        ?>
        <select id="salarieids" name="salarieid">
          <?php
            while ($row = mysql_fetch_assoc($result)) {
              echo '<option value="', $row['salaried'], '">', $row['salaried'], '</option>'; //between <option></option> tags you can output something more human-friendly (like $row['name'], if table "salaried" have one)
            }
          ?>
        </select>
        <?php endif ?>
      </p>
      <p>
        <input type="submit" value="Sumbit my choice"/>
      </p>
    </form>

    <?php if isset($_POST['salaried']) : ?>
      <?php
        $query = "SELECT * FROM salarie WHERE salarieid = " . $_POST['salarieid'];
        $result = mysql_query($query);
        if ($result) :
      ?>
        <table>
          <?php
            while ($row = mysql_fetch_assoc($result)) {
              echo '<tr>';
              echo '<td>', $row['salaried'], '</td><td>', $row['bla-bla-bla'], '</td>' ...; // and others
              echo '</tr>';
            }
          ?>
        </table>
      <?php endif?>
    <?php endif ?>
  </body>
</html>

回答by Christian

Just save it in a cookie:

只需将其保存在 cookie 中:

$(document).ready(function () {
  createCookie("height", $(window).height(), "10");
});

function createCookie(name, value, days) {
  var expires;
  if (days) {
    var date = new Date();
    date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
    expires = "; expires=" + date.toGMTString();
  }
  else {
    expires = "";
  }
  document.cookie = escape(name) + "=" + escape(value) + expires + "; path=/";
}

And then read it with PHP:

然后用PHP读取它:

<?PHP
   $_COOKIE["height"];
?>

It's not a pretty solution, but it works.

这不是一个很好的解决方案,但它有效。

回答by user1849393

There are several ways of passing variables from JavaScript to PHP (not the current page, of course).

有多种方法可以将变量从 JavaScript 传递到 PHP(当然不是当前页面)。

You could:

你可以:

  1. Send the information in a form as stated here (will result in a page refresh)
  2. Pass it in Ajax (several posts are on here about that) (without a page refresh)
  3. Make an HTTP request via an XMLHttpRequest request (without a page refresh) like this:
  1. 以此处所述的形式发送信息(将导致页面刷新)
  2. 在 Ajax 中传递它(这里有几篇关于这个的帖子)(没有页面刷新)
  3. 通过 XMLHttpRequest 请求(不刷新页面)发出 HTTP 请求,如下所示:


 if (window.XMLHttpRequest){
     xmlhttp = new XMLHttpRequest();
 }

else{
     xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
 }

 var PageToSendTo = "nowitworks.php?";
 var MyVariable = "variableData";
 var VariablePlaceholder = "variableName=";
 var UrlToSend = PageToSendTo + VariablePlaceholder + MyVariable;

 xmlhttp.open("GET", UrlToSend, false);
 xmlhttp.send();

I'm sure this could be made to look fancier and loop through all the variables and whatnot - but I've kept it basic as to make it easier to understand for the novices.

我确信这可以使它看起来更漂亮,并循环遍历所有变量等等——但我保持了它的基本性,以便让新手更容易理解。

回答by Arslan Tabassum

Here is the Working example: Get javascript variable value on the same page in php.

这是工作示例:在 php 中的同一页面上获取 javascript 变量值。

<script>
var p1 = "success";
</script>

<?php
echo "<script>document.writeln(p1);</script>";
?>

回答by Terry Prothero

I was trying to figure this out myself and then realized that the problem is that this is kind of a backwards way of looking at the situation. Rather than trying to pass things from JavaScript to php, maybe it's best to go the other way around, in most cases. PHP code executes on the server and creates the html code (and possibly java script as well). Then the browser loads the page and executes the html and java script.

我试图自己弄清楚这一点,然后意识到问题在于,这是一种倒退的看待情况的方式。在大多数情况下,与其尝试将东西从 JavaScript 传递到 php,也许最好反过来。PHP 代码在服务器上执行并创建 html 代码(也可能是 java 脚本)。然后浏览器加载页面并执行 html 和 java 脚本。

It seems like the sensible way to approach situations like this is to use the PHP to create the JavaScript and the html you want and then to use the JavaScript in the page to do whatever PHP can't do. It seems like this would give you the benefits of both PHP and JavaScript in a fairly simple and straight forward way.

似乎处理这种情况的明智方法是使用 PHP 创建您想要的 JavaScript 和 html,然后在页面中使用 JavaScript 来完成 PHP 无法完成的任何操作。看起来这会以一种相当简单和直接的方式为您提供 PHP 和 JavaScript 的好处。

One thing I've done that gives the appearance of passing things to PHP from your page on the fly is using the html image tag to call on PHP code. Something like this:

我所做的一件事是使用 html 图像标记来调用 PHP 代码,这让我看起来像是在运行中将内容从您的页面传递给 PHP。像这样的东西:

<img src="pic.php">

The PHP code in pic.php would actually create html code before your web page was even loaded, but that html code is basically called upon on the fly. The php code here can be used to create a picture on your page, but it can have any commands you like besides that in it. Maybe it changes the contents of some files on your server, etc. The upside of this is that the php code can be executed from html and I assume JavaScript, but the down side is that the only output it can put on your page is an image. You also have the option of passing variables to the php code through parameters in the url. Page counters will use this technique in many cases.

pic.php 中的 PHP 代码实际上会在您的网页加载之前创建 html 代码,但该 html 代码基本上是即时调用的。此处的 php 代码可用于在您的页面上创建图片,但除此之外,它还可以包含您喜欢的任何命令。也许它会更改您服务器上某些文件的内容等。这样做的好处是可以从 html 执行 php 代码,我假设是 JavaScript,但缺点是它可以放在您的页面上的唯一输出是图片。您还可以选择通过 url 中的参数将变量传递给 php 代码。页计数器将在许多情况下使用这种技术。

回答by Derek H

PHP runs on the server before the page is sent to the user, JavaScript is run on the user's computer once it is received, so the PHP script has already executed.

PHP在页面发送给用户之前在服务器上运行,JavaScript一旦收到就在用户的计算机上运行,​​所以PHP脚本已经执行了。

If you want to pass a JavaScript value to a PHP script, you'd have to do an XMLHttpRequest to send the data back to the server.

如果要将 JavaScript 值传递给 PHP 脚本,则必须执行 XMLHttpRequest 将数据发送回服务器。

Here's a previous question that you can follow for more information: Ajax Tutorial

这是您可以关注的先前问题以获取更多信息:Ajax 教程

Now if you just need to pass a form value to the server, you can also just do a normal form post, that does the same thing, but the whole page has to be refreshed.

现在,如果您只需要向服务器传递一个表单值,您也可以只做一个普通的表单发布,做同样的事情,但必须刷新整个页面。

<?php
if(isset($_POST))
{
  print_r($_POST);
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
  <input type="text" name="data" value="1" />
  <input type="submit" value="Submit" />
</form>

Clicking submit will submit the page, and print out the submitted data.

点击提交将提交页面,并打印出提交的数据。

回答by VisionQuest

Here's how I did it (I needed to insert a local timezone into PHP:

这是我的做法(我需要在 PHP 中插入一个本地时区:

<?php
    ob_start();
?>

<script type="text/javascript">

    var d = new Date();
    document.write(d.getTimezoneOffset());
</script>

<?php
    $offset = ob_get_clean();
    print_r($offset);

回答by Tushar Walzade

We can easily pass values even on same/ different pages using the cookies shown in the code as follows (In my case, I'm using it with facebook integration) -

即使在相同/不同的页面上,我们也可以使用代码中显示的 cookie 轻松传递值,如下所示(在我的情况下,我将它与 facebook 集成一起使用)-

function statusChangeCallback(response) {
    console.log('statusChangeCallback');
    if (response.status === 'connected') {
        // Logged into your app and Facebook.
        FB.api('/me?fields=id,first_name,last_name,email', function (result) {
            document.cookie = "fbdata = " + result.id + "," + result.first_name + "," + result.last_name + "," + result.email;
            console.log(document.cookie);
        });
    }
}

And I've accessed it (in any file) using -

我已经使用 - 访问了它(在任何文件中)

<?php 
    if(isset($_COOKIE['fbdata'])) { 
        echo "welcome ".$_COOKIE['fbdata'];
    }
?>

回答by Sayed Mohd Ali

when your page first loads the PHP code first run and set the complete layout of your webpage. after the page layout, it set the JavaScript load up. now JavaScript directly interacts with DOM and can manipulate the layout but PHP can't it needs to refresh the page. There is only way is to refresh your page to and pass the parameters in the page URL so that you can get the data via PHP. So we use AJAX to interact Javascript with PHP without page reload. AJAX can also be used as an API. one more thing if you have already declared the variable in PHP. before the page load then you can use it with your Javascript example.

当您的页面首次加载 PHP 代码时,首先运行并设置您网页的完整布局。在页面布局之后,它设置了 JavaScript 加载。现在 JavaScript 直接与 DOM 交互并且可以操作布局,但 PHP 不能它需要刷新页面。唯一的方法是刷新页面并在页面 URL 中传递参数,以便您可以通过 PHP 获取数据。所以我们使用 AJAX 与 PHP 交互,无需重新加载页面。AJAX 也可以用作 API。如果您已经在 PHP 中声明了变量,还有一件事。在页面加载之前,您可以将它与您的 Javascript 示例一起使用。

<script>
var username = "<?php echo $myname;?>";
alert(username);
</script>

the above code is correct and it will work. but the code below is totally wrong and it will never work.

上面的代码是正确的,它会工作。但下面的代码是完全错误的,它永远不会工作。

<script>
    var username = "syed ali";
    var <?php $myname;?> = username;
    alert(myname);
    </script>
  • Pass value from JavaScript to PHP via AJAX

    it is the most secure way to do it. because HTML content can be edited via developer tools and the user can manipulate the data. so it is better to use AJAX if you want security over that variable.if you are a newbie to AJAX please learn AJAX it is very simple.

  • 通过 AJAX 将值从 JavaScript 传递到 PHP

    这是最安全的方法。因为 HTML 内容可以通过开发人员工具进行编辑,用户可以操作数据。因此,如果您想要对该变量的安全性,最好使用 AJAX。如果您是 AJAX 的新手,请学习 AJAX,它非常简单。

The best and most secure way to pass JavaScript variable into PHP is via AJAX

将 JavaScript 变量传递到 PHP 的最佳和最安全的方法是通过 AJAX

simple AJAX example

简单的 AJAX 示例

var mydata = 55;
var myname = "syed ali";
var userdata = {'id':mydata,'name':myname};
    $.ajax({
            type: "POST",
            url: "YOUR PHP URL HERE",
            data:userdata, 
            success: function(data){
                console.log(data);
            }
            });
  • PASS value from javascript to php via hidden fields.
  • 通过隐藏字段将值从 javascript 传递到 php。

otherwise, you can create hidden HTML input inside your form. like

否则,您可以在表单中创建隐藏的 HTML 输入。喜欢

<input type="hidden" id="mydata">

then via jQuery or javaScript pass the value to the hidden field. like

然后通过 jQuery 或 javaScript 将值传递给隐藏字段。喜欢

<script>
var myvalue = 55;
$("#mydata").val(myvalue);
</script>

Now when you submit the form you can get the value in PHP.

现在,当您提交表单时,您可以获得 PHP 中的值。

回答by user3822447

Your code has a few things wrong with it.

您的代码有一些问题。

  • You define a JavaScript function, func_load3(), but do not call it.
  • Your function is defined in the wrong place. When it is defined in your page, the HTML objects it refers to have not yet been loaded. Most JavaScript code checks whether the document is fully loaded before executing, or you can just move your code past the elements it refers to in the page.
  • Your form has no means to submit it. It needs a submit button.
  • You do not check whether your form has been submitted.
  • 您定义了一个 JavaScript 函数 func_load3(),但不调用它。
  • 你的函数定义在错误的地方。当它在您的页面中定义时,它所引用的 HTML 对象尚未加载。大多数 JavaScript 代码会在执行之前检查文档是否已完全加载,或者您可以将代码移动到它在页面中引用的元素之外。
  • 您的表单无法提交。它需要一个提交按钮。
  • 您不会检查您的表单是否已提交。

It is possible to set a JavaScript variable in a hidden variable in a form, then submit it, and read the value back in PHP. Here is a simple example that shows this:

可以在表单的隐藏变量中设置 JavaScript 变量,然后提交它,然后在 PHP 中读取该值。这是一个简单的例子,说明了这一点:

<?php
if (isset($_POST['hidden1'])) {
   echo "You submitted {$_POST['hidden1']}";
   die;
}

echo <<<HTML
   <form name="myform" action="{$_SERVER['PHP_SELF']}" method="post" id="myform">
      <input type="submit" name="submit" value="Test this mess!" />
      <input type="hidden" name="hidden1" id="hidden1" />
   </form>

   <script type="text/javascript">
      document.getElementById("hidden1").value = "This is an example";
   </script>
HTML;
?>