php - 如何将数据从 JavaScript 发送到 PHP,反之亦然?

标签 php javascript html protocols

<分区>

如何将数据从 JavaScript 代码传递到 PHP 并返回。 现在,我这样做是一种迂回的方式:
PHP 到 JavaScript: 我会简单地使用内联回显来发送数据:

<script type="text/javascript">
    var data = <? echo $target_variable ?>
</script>

<script type="text/javascript">
    var data = <?= $target_variable ?>
</script>

JavaScript 到 PHP: 我会在 JavaScript 中创建一个表单元素,它将我的数据汇总到 php 文件中:

<script type="text/javascript">
    var data = targetData;
    document.write("
        <form method=\"post\">
            <input type=\"hidden\" value=\""+target_value+\""></input>
        </form>
    ");
</script>
</script>

有没有更好的方法来做到这一点?最佳实践之类的东西。

最佳答案

如果您希望通过表单提交此数据,则无需使用 Javascript 创建表单。只需使用 HTML 创建一个不可见的表单,使用 Javascript 填充隐藏字段,并在您准备就绪时自动提交。

  <form method="post" action="process.php">
    <input type="hidden" name="data" id="data" />
  </form>

  document.getElementById("data").value = "foo";

如果您想以 ajax 风格的方式发送它,我建议您实现 jQuery,这使得这非常容易。请注意之前的案例转换为 jQuery 解决方案:

$.post("process.php", {data:"foo"}, function(results){
  // the output of the response is now handled via a variable call 'results'
  alert(results);
});

关于php - 如何将数据从 JavaScript 发送到 PHP,反之亦然?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1968296/

相关文章:

javascript - ember 核心表单组件中的 ARIA 属性

javascript - 在 javascript 中将响应正文 blob 转换为 json 或纯文本

html - spring mvc 向收件人发送时尚且格式化的电子邮件

javascript - PHP/JavaScript : See if someone is visiting the same url

javascript - Laravel 中未显示 Vue 组件

php - 每五个字拆分字符串

javascript - 从 openpyxl.chart.title 导入标题 - AttributeError : 'list' object has no attribute

php - Smarty(和其他 tpl ngins): assign and assign_by_ref

html - Perl Mechanize : Get the response page after the page is modified?

html - 使用分隔线垂直间隔