使用ajax将JS变量传递给PHP [英] Pass JS variable to PHP using ajax

查看:95
本文介绍了使用ajax将JS变量传递给PHP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这里已经有人问过这个问题,但是我发现的答案都没有回答我的问题.

I know this has been asked on here but none of the answers I found answered my question.

我有一个供用户查看的PHP/HTML文件.当他们单击按钮时,它会创建一个JS变量,我想将其转换为PHP变量.使用该变量,我想通过调用PHP函数来更新div框的内容,该函数使用服务器中的信息填充该框.

I have a PHP/HTML file that the users view. When they click on a button, it creates a JS variable which I would like translated into a PHP variable. 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.

我的问题:可以仅用1个php文件吗?刷新内容后,我是否必须让用户重新加载页面?最好的方法是什么?

My questions: Can this be done with only 1 php file? Do I have to have the user reload the page after I refresh the content? What is the best way to do this?

推荐答案

您可以避免用户重新加载页面,但这需要AJAX.这就提出了一个问题-是否需要在没有JavaScript的情况下工作?

You can avoid the user reloading the page, but that would require AJAX. That raises the question - Does this need to work without JavaScript?

如果您对这取决于JavaScript感到满意,则可以使用AJAX帖子,例如使用JQuery的帖子:

If you are happy for this to be dependant on JavaScript you could use an AJAX post, such as this using JQuery:

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

example.php是一个不同的.php文件,在example.php中,您将处理 variableName 的值并生成所需的标记,该标记将显示在原始页面中.如果您需要在不使用JavaScript的情况下工作,那么我建议您重新加载页面.

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. If you need this to work without JavaScript then I would suggest reloading the page.

这篇关于使用ajax将JS变量传递给PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆