简体   繁体   English

如何将jquery中的值存储到php变量中?

[英]How to store a value from jquery into a php variable?

Is there a way to store a value that is retrieved from Jquery into a php variable? 有没有办法将从Jquery检索到的值存储到php变量中? The jquery value that I want to store in a php variable is this: 我想要存储在php变量中的jquery值是这样的:

$(this).attr("title");

How can I store this into a php variable ? 如何将其存储到php变量中? Is there a way ? 有办法吗?

Your question is a little vague but the short answer is no. 你的问题有点模糊,但简短的回答是否定的。 However, you can use jQuery to make an AJAX server request to PHP and transfer your data to the server-side that way, of course. 但是,您可以使用jQuery向PHP发出AJAX服务器请求,并以这种方式将数据传输到服务器端。

Example: 例:

JQUERY: JQUERY:

        var theTitle = $(this).attr("title");

        $.ajax({
            url: '/URL/TO/PHP/FILE.php',
            type: 'POST',
            data: {
                title: theTitle
            },
            success: function( data )
            {
              //data is whatever your PHP script returns
            },
            error: function(xhr) {
              // if your PHP script return an erroneous header, you'll land here
            }
        });

and PHP: 和PHP:

        <?php

          if ( $_POST ) {

            echo $_POST[ 'title' ];  // this is what you passed from jQuery

          }

        ?>

You've got 2 options: 你有两个选择:

  1. use an AJAX request to send the variable's value back to the server 使用AJAX请求将变量的值发送回服务器
  2. use a form to submit the value 使用表单提交值

Remember that PHP runs on a server, and its execution has terminated LONG before the javascript code ever starts running on the client. 请记住,PHP在服务器上运行,并且在javascript代码开始在客户端上运行之前,它的执行已经终止。

No, of course that it's not possible. 不,当然,这是不可能的。 Not only that it is not possible but it doesn't make any sense. 这不仅是不可能的,而且没有任何意义。 PHP runs on the server, jQuery on the client much later after the PHP script has finished executing. 在PHP脚本执行完毕后,PHP在服务器上运行,客户端上的jQuery很晚。 So there are no any PHP variables by the time jQuery script runs on the client. 因此,当jQuery脚本在客户端上运行时,没有任何PHP变量。

So you could either send the value back using a form, link or AJAX call to the server. 因此,您可以使用表单,链接或AJAX调用将值发送回服务器。

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

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