将 JavaScript 变量发送到 PHP 变量 [英] Send JavaScript variable to PHP variable

查看:36
本文介绍了将 JavaScript 变量发送到 PHP 变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

起初我认为我必须将 JavaScript 转换为 PHP,但后来我发现我不能,因为服务器和客户端执行.所以现在我只想发送一个变量

First I thought that I had to convert JavaScript to PHP, but then I found out that I cannot because of server and client side executions. So now I simply want to send ONE variable

<script type="text/javascript">
function scriptvariable()
{        
    var theContents = "the variable";
}
</script>

到一个 PHP 变量

<?php
$phpvariable
?>

假设我点击一个按钮时,JavaScript 中的那个函数就会执行.

That function in the JavaScript executes when let's say I click on a button.

现在我不知道如何将该 phpvariable 分配给 JavaScript 以使用 phpvariable 在我的数据库中查找内容.我知道我可以将它添加到我的 url 或其他东西并刷新页面,但我想用 AJAX 来做,因为我可能不得不在我的网页中进一步使用这个 Ajax 方法.

Now I have no idea on how to assign that phpvariable to the JavaScript one to use the phpvariable to look up stuff in my database. I know I can add it to my url or some thing and refresh the page, but I would like to do it with AJAX as I might have to use this Ajax method further in my webpage.

那么有没有一种简单的方法可以做到这一点,而不必在我的页面上转储代码页来做一件简单的事情?

So is there an easy way to do this without having to dump pages of code on my page to do one simple thing?

推荐答案

正如 Jordan 已经说过的,您必须先将 javascript 变量回发到服务器,然后服务器才能处理该值.为此,您可以编写一个提交表单的 javascript 函数 - 或者您可以使用 ajax/jquery.jQuery.post

As Jordan already said you have to post back the javascript variable to your server before the server can handle the value. To do this you can either program a javascript function that submits a form - or you can use ajax / jquery. jQuery.post

也许对你来说最简单的方法是这样的

Maybe the most easiest approach for you is something like this

function myJavascriptFunction() { 
  var javascriptVariable = "John";
  window.location.href = "myphpfile.php?name=" + javascriptVariable; 
}

在您的 myphpfile.php 上,您可以在执行 javascript 后使用 $_GET['name'].

On your myphpfile.php you can use $_GET['name'] after your javascript was executed.

问候

这篇关于将 JavaScript 变量发送到 PHP 变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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