javascript - 通过 Ajax 将 JavaScript 函数传递给 PHP 文件

标签 javascript php jquery html ajax

我想做的事情:

我正在编写一个脚本,旨在为用户提供选择,并根据他们所做的选择,提出一个新的选择。我为此制作了两个脚本,一个用于 HTML 和页面结构,一个用于 PHP(从服务器获取信息)和 JavaScript(构建生成的选择)。

然后,我使用 AJAX 在这两个脚本之间进行通信,或者至少,这就是我正在尝试做的事情,但我对 AJAX 非常陌生,无法使其工作。

当按下 3 个按钮之一时,我试图从我的页面传递或以某种方式启动函数'generateProblems',最好使用参数'id'

这是我的index.html的一部分:

            <div id="testpile" class="inner cover">
                <div id="buttons">
                    <p><a id="rat" class="btn btn-default" role="button">Rationel</a></p>
                    <p><a id="emo" class="btn btn-default" role="button">Emotionel</a></p>
                    <p><a id="per" class="btn btn-default" role="button">Personel</a></p>
                </div>
            </div>

            <div id="testdrop" class="mastfoot">
                <p>Drop numbers here</p>
            </div>

<script type="text/javascript">
    $("#buttons").find(".btn").click(function() {
        var id = this.id;
        $("#testpile").load("include/responseget.php");
        $.post("include/responseget.php", {
            choice: "id",
        });
    });

</script>

这是我的 PHP/Javascript:

<?php  include 'login.php';
//Query til at finde information til generation af question
$stmt = $conn->prepare("SELECT DISTINCT ResponseTitle, ResponseText FROM response Limit 8;");
$stmt->execute();
$result = $stmt->get_result();

  while($row = $result->fetch_assoc()) 
  {
      $rTitle_array[] = $row['ResponseTitle'];
      $rText_array[] = $row['ResponseText'];
  }

json_encode($rTitle_array);
json_encode($rText_array);

// close connection
mysqli_close($conn);
?>
<script type="text/javascript">
    $(function() {
        var phase = 0;
        var rTitle = <?php echo json_encode($rTitle_array); ?>;
        var rText = <?php echo json_encode($rText_array); ?>;

        function generateProblems(param) {
            var problemDef = param;
            $("#buttons").hide();
            var numbers = [1, 2, 3, 4, 5, 6, 7, 8];
            for (var i = 0; i < 8; i++) {
                $('<div>' + rTitle[i] + '</div>').data('number', rTitle[i]).attr('id', 'problem' + rTitle[i]).appendTo('#testpile').draggable({
                    containment: '.site-wrapper',
                    stack: '#testpile div',
                    cursor: 'move',
                    revert: true
                });
                $('<div>' + rText[i] + '</div>').data('number', rText[i]).attr('id', 'problem' + rText[i]).appendTo('#testpile');
            }


            $('#testdrop').droppable({
                drop: handleDropEvent,
                accept: '#testpile div'
            });


            function handleDropEvent(event, ui) {
                var problemNumber = ui.draggable.data('number');
                var problemCombination = problemDef + problemNumber;
                ui.draggable.draggable('disable');
                ui.draggable.draggable('option', 'revert', false);
                phase++;
                alert('ProblemCombination is "' + problemCombination + '", phase is "' + phase + '" ');
                $("#testpile").children().hide();

                generateProblems(problemCombination);

            }
        }

    });

</script>

我做错了什么?在我将其拆分之前,该代码运行得很好,但现在单击其中一个按钮不会产生任何结果。

最佳答案

这不是正确的做法。让你的 php 远离 html/js。您无法从未直接包含在其中的其他脚本访问您的 html。

  1. 将您的 JavaScript 部分重新添加到 index.html
  2. 在你的 php 脚本中返回 最后的东西像 return json_encode($rTitle_array);
  3. 在你的 jquery/ajax post,获取返回值并使用

来自 jquery 文档的示例:

  var posting = $.post( url, { s: term } );

  // Put the results in a div
  posting.done(function( data ) {
    var content = $( data ).find( "#content" );
    $( "#result" ).empty().append( content );
  });

关于javascript - 通过 Ajax 将 JavaScript 函数传递给 PHP 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37326365/

相关文章:

javascript - 获取 xmlHTTP 请求不起作用

javascript - 如何在 $(window).resize() 中的 $(this) 上使用 e.preventDefault()?

php - 从继承的 Controller 调用表单

javascript - 根据动态内容动态调整div的大小?

jquery - 提高 JSON 格式数据检索的性能

javascript - JQuery 代码语法问题? ("Inline control structures are not allowed")

javascript - ng-repeat 不输出 JSON 数据

php - Mailchimp 通过 api 取消设置合并变量

PHP PDO无法删除记录

javascript - jquery ajax html 警报中的 "\r\n\"