简体   繁体   English

使用ajax将JS变量传递给PHP

[英]Pass JS variable to PHP using ajax

I know this has been asked on here but none of the answers I found answered my question. 我知道这里已经有人问过了,但是我没有找到答案。

I have a PHP/HTML file that the users view. 我有一个供用户查看的PHP / HTML文件。 When they click on a button, it creates a JS variable which I would like translated into a PHP variable. 当他们单击按钮时,它将创建一个JS变量,我想将其转换为PHP变量。 Using that variable, I would like to update the contents of a div box by calling a PHP function which populates the box with info from the server. 使用该变量,我想通过调用PHP函数来更新div框的内容,该函数使用服务器中的信息填充该框。

My questions: Can this be done with only 1 php file? 我的问题:只能用1个php文件吗? Do I have to have the user reload the page after I refresh the content? 刷新内容后是否需要让用户重新加载页面? What is the best way to do this? 做这个的最好方式是什么?

You can avoid the user reloading the page, but that would require AJAX. 您可以避免用户重新加载页面,但这需要AJAX。 That raises the question - Does this need to work without JavaScript? 这就提出了一个问题-是否需要在没有JavaScript的情况下工作?

If you are happy for this to be dependant on JavaScript you could use an AJAX post, such as this using JQuery: 如果您对依赖于JavaScript感到满意,则可以使用AJAX帖子,例如使用JQuery:

$.post( "example.php", { variableName: "example" })
  .done(function( response ) {
    $('.example-output').html( response );
  });

example.php would be a different .php file, in example.php you would process the value of variableName and produce the required markup, which would be displayed in the original page. example.php是一个不同的.php文件,在example.php中,您将处理variableName的值并生成所需的标记,该标记将显示在原始页面中。 If you need this to work without JavaScript then I would suggest reloading the page. 如果您需要在没有JavaScript的情况下工作,那么我建议您重新加载页面。

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

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