0

I have two Javascript functions that will return values. I have little experience in JS and PHP, so what I was wondering - is how would I append the variables to a hidden field, and get them with PHP so I can perform some arithmetic with it, and return a final value which I can then display.

I can do the last part (calculate the last value, and display it). I was wondering how I could post the variables from the JS function, and get them with PHP saving them to a PHP variable WITHOUT USER INTERACTION - This is the most important part, it needs to be done automatically.

Thanks in advance,

4

2 回答 2

0

对此有多种解决方案。

您可以将值插入查询字符串并重新加载页面。

function send_to_php(var value) {
    window.location.assign("mypage.php?value=" + value);
}

在 PHP 中,它存储在$_GET['value']and中$_REQUEST['value']

您还可以将值放在表单中的隐藏输入字段中并运行

document.getElementById('my_form').submit()

如果您不希望页面重新加载,您应该使用 AJAX:http ://www.w3schools.com/ajax/

编辑:

要在 JavaScript 中运行函数而不使用交互,只需在脚本内的任何位置调用函数,例如send_to_php(44);. 您也可以setTimeout("send_to_php(44)", 10000)在调用函数之前等待 10 秒。

如果您希望函数多次运行,请setTimeout在函数结束时再次调用。

于 2013-10-13T22:48:02.877 回答
0

一种快速的方法是使用 AJAX(异步 Javascript 和 XML)。

JavaScript

$.post("/myfile.php", {phpvariable: javascriptvariable}, function(data) {
   // Do something after successfully sent.
   // e.g. location.reload();
 });

这将向您发送一个 POST 变量,而无需与指定的 PHP 文件进行任何用户交互。

我的文件.php

<?php
   $javascriptvariable = $_POST['phpvariable'];
?>
于 2013-10-13T22:50:11.637 回答