想在php中将2个JavaScript变量写入文件

时间:2015-03-22 19:15:35

标签: javascript php ajax

尝试使用AJAX将2个JS变量传递到我的PHP页面。一个变量只是时间,另一个是一串用户输入。我不知道如何从模态表单获取用户输入,我想在GET中提交这些变量并将它们写入leaders.txt文件。

            var d = new Date();
            var t = d.getTime();
            var rec = (t - time)/1000
            alert("Time = " + rec + " seconds!");
            var modal = document.getElementById("userName");
            $(modal).modal('show');
            var xmlhttp = new XMLHttpRequest();
            xmlhttp.open("GET","index.php?time=" + rec, true);
            xmlhttp.send();

            <div class="modal fade in" id="userName" tabindex="-1" role="dialog"
                    aria-labelledby="myModalLabel" aria-hidden="true">
                        <div class="modal-dialog">
                            <div class="modal-content">
                                <div class="modal-header">
                                    <button type="button" class="close" data-dismiss="modal"
                                    aria-hidden="true">&times;</button>
                                    <h4 class="modal-title" id="myModalLabel">Add your name to the leader board!</h4>
                                </div>
                                <div class="modal-body">
                                        <form method="get" action="index.php" role="form">
                                            <div class="form-group">
                                                <label for="usr">Arcade Name:</label>
                                                <input type="text" class="form-control" id="usr">
                                            </div>
                                        <button type="submit" class="btn btn-default">Submit</button>
                                    </form>
                                </div>
                            </div><!-- /.modal-dialog -->
                        </div><!-- /.modal -->
                    </div>
                <?php
                    $time = $_GET["time"];
                    if($time != ""){
                        $name = $_GET["name"];
                        console.log($time + $name);
                        file_put_contents("leader.txt", $name.':'.$time."\n", FILE_APPEND);
                    }
                ?>

1 个答案:

答案 0 :(得分:1)

将代码xmlhttp.open("GET","index.php?time=" + rec, true);中的代码更改为xmlhttp.open("GET","index.php?time=" + rec+"&modal="+modal,true);

并在index.php $_GET['model']中获取此变量。