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

问题描述:

我如何着手将JavaScript代码中的数据传递给PHP并返回。
现在,我这样做是一回事:

PHP to JavaScript:
我只需使用内联回显来发送数据:

How do I go about passing data from JavaScript code to PHP and back. Right now, I do this is a round about way:
PHP to JavaScript: I would simply use the inline echo to send the data:

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

OR

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

JavaScript到PHP:
我会在JavaScript中创建一个表单元素,数据为我的PHP文件:

JavaScript to PHP: I would create a form element in the JavaScript that would sumbit the data for me to the php file:

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

有没有更好的方法可以做到这一点?最佳实践之类的事情。

Are there any better ways to do this? Best practices sort of thing.

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

If you wish to submit this data via a form, you don't need to create the form with Javascript. Simply create an invisible form with HTML, populate the hidden field with Javascript, and automatically submit whenever you're ready.

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

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

如果你想以ajax风格发送这个,我会建议实现jQuery,这非常简单。注意前面的例子转换为jQuery解决方案:

If you want to send this in an ajax-style fashion, I would suggest implementing jQuery, which makes this extremely easy. Note the previous case converted to a jQuery solution:

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