【问题标题】:Pass variable from Javascript to PHP to write to file将变量从 Javascript 传递到 PHP 以写入文件
【发布时间】:2015-06-22 14:01:15
【问题描述】:

这可能是重复的原因,即使通过搜索 Stackoverflow 的类似问题也无法找到答案。这就是我想要做的。我需要将 JavaScript 中的存储变量传递给 PHP,PHP 会将其写入临时文件“yy.html”。我可以从提交功能获得警报,但不是临时文件。当我单独运行 PHP 时,我得到了临时文件。

g.htm

<html>
<head><title>Hide and Seek</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js/jquery.min.js">
</script>
</head>
<body>
<span id = "nextbutton"></span>
<script type="text/javascript">
res = "Hide & Seek";
document.getElementById('nextbutton').innerHTML = '<button type="submit" class="btn-u btn-u-default" OnClick="javascript:submit()">Restart</button>&nbsp;&nbsp';
function submit()
{
alert(res);
$.post('my.php', { postres: res} );
}
</script>
</body>
</html>

my.php

<?php $res = $_POST['postres']; $temp = getenv("TEMP"); file_put_contents($temp . "/yy.html", $res); ?>

【问题讨论】:

标签: javascript php html post


【解决方案1】:

首先在&lt;head&gt;中添加jQuery库:

<head>
   ..
   <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js/jquery.min.js">
   ..
</head>

然后,用 Ajax 试试这个:

$.ajax({
  type: "POST",
  url: "my.php",
  data: { postres: res }
});

【讨论】:

  • 唷!你救了我的命,因为我用 $.post 打了几个小时的墙。谢谢。
【解决方案2】:

试试 $temp = sys_get_temp_dir();在你的 php 文件中。

【讨论】:

  • 还要确保您访问的是正确的临时目录。
  • 谢谢。我一定会的。
猜你喜欢
  • 1970-01-01
  • 2016-10-14
  • 2012-10-07
  • 2017-06-30
  • 1970-01-01
  • 1970-01-01
  • 2014-09-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多