【问题标题】:Theoretical Q: From PHP to Specific Part of Javascript理论问题:从 PHP 到 Javascript 的特定部分
【发布时间】:2014-03-19 05:34:02
【问题描述】:

假设我有以下 HTML 文档,它执行某种简单的计算:

<html>
<script>

for (i=0;i<10;i++) {
    var x = 2*i;
    // send to PHP
};

</script>
</html>

现在假设我想通过连续将 x 值发送到单独的 PHP 文档(如下所示)将 x 值保存到文本文件,该文档会将值附加到文本文件,然后返回到 HTML 进行循环中的下一个计算。

<?php
    $my_file = 'results.txt';
    $handle = fopen($my_file, 'a') or die('Cannot open file:  '.$my_file);
    fwrite($handle,$_POST["x"]."\n");
    fclose($handle);
    // go back to HTML document, BUT pick up from i+1 (i.e., don't start over from i=0)
?>

有人知道这是否可能吗?如果是这样,我应该在那些注释行中写什么?对我来说重要的是,我实际上坚持这种在 i 的下一个值处获取 HTML 文档的方法(而不是在一个 PHP 文件中进行整个计算),因为这只是一个概念证明。

【问题讨论】:

  • Ajax 可能是您正在寻找的
  • 绝对是 AJAX,如果你做异步 AJAX,循环将在服务器响应你的 HTML 页面之前继续,同步将保持 JS 执行直到服务器响应,这取决于你需要什么
  • 假设您可能应该重新考虑您正在尝试做的任何事情,这可能是安全的。通过 for 循环发送 10 个 ajax 请求听起来像是坏消息。

标签: javascript php html loops iteration


【解决方案1】:

您想使用 JQuery Ajax。但是,最好先将所有 x 值放入一个数组中,然后再发送该数组。 html/jQuery 看起来像这样:

<script type="text/javascript">

    $(document).ready(function(){
        //intiialize array
        var myArray = [];
        for(i = 0; i < 10; ++i){
            myArray.push(i); // uses push() method to insert each number to array
        };

        $.post("yourFile.php",
               {TheArray: myArray}, // notice how the array is posted 
            function(response){
                alert(response); //simply alerts the response
            });

    });


    </script>

PHP 是这样的:

<?php

$data = array();

$data = $_REQUEST['TheArray']; // could use post, but request works too

var_dump($data); //cannot echo an array, only strings

?>

【讨论】:

    猜你喜欢
    • 2019-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-18
    • 1970-01-01
    相关资源
    最近更新 更多