简体   繁体   English

通过Ajax将JavaScript函数传递到PHP文件

[英]Pass JavaScript function through Ajax to PHP file

What I am trying to do: 我正在尝试做的是:

I am working on a script intending to offer the user choices and depending on which choice they make, come up with a new choice. 我正在编写一个脚本,旨在为用户提供选择,并根据他们做出的选择提供新的选择。 I have made two scripts for this, one for my HTML and the structure of my page and one for my PHP (getting the information from my server) and JavaScript (building the generated choices). 为此,我编写了两个脚本,一个用于HTML和页面结构,一个用于PHP(从服务器获取信息)和JavaScript(构建生成的选择)。

I am then using AJAX to communicate between these two scripts, or at least, that's what I am trying to do, but I am very new when it comes to AJAX and I cannot make it work. 然后,我正在使用AJAX在这两个脚本之间进行通信,或者至少是我正在尝试做的事情,但是当涉及到AJAX时我还是很陌生,我无法使其正常工作。

I am trying to pass or somehow start the function 'generateProblems' from my page when one of the 3 buttons are pressed, preferably with the param 'id' . 当我按下3个按钮之一时,我试图传递或以某种方式启动页面中的“ generateProblems”功能,最好使用参数“ id”

Here's part of my index.html: 这是我的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>

And here's my PHP / Javascript: 这是我的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>

What am I doing wrong? 我究竟做错了什么? The code worked pretty well before I split it up, but now clicking one of the buttons generate nothing. 在拆分之前,该代码运行良好,但是现在单击其中一个按钮不会产生任何效果。

This is not the right way to do. 这不是正确的方法。 Keep your php away from html/js. 使您的php远离html / js。 You can't access to your html from another script which is not directly included in it. 您无法通过未直接包含在其中的另一个脚本访问html。

  1. Re-add your javascript part to index.html 将您的javascript部分重新添加到index.html
  2. In your php script return something at the end like return json_encode($rTitle_array); 在您的php脚本中,最后返回一些内容,例如return json_encode($rTitle_array);
  3. In your jquery/ajax post, get the returned value and use it 在您的jquery / ajax帖子中,获取返回值并使用它

A sample from the jquery doc: 来自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 );
  });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM