如何通过触发第二页的返回来触发方法?

时间:2019-03-06 17:57:00

标签: javascript php css ajax

Page1.php

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js" type="text/javascript"></script>

    <input type="hidden" value="valuetest" id="idinput">

    <div onclick="myfunction()" style="height: 30px;width: 30px;background: gray;">
        <div id="receive"></div>
    </div>

    <script type="text/javascript">
        function myfunction() {
          $.ajax({
            type: "POST",
            url: "page2.php",
            data: {
              sendpost: $('#idinput').val()
            },
            success: function(data) {
              $('#receive').html(data);
            }
          });

         function myfunction2(){

         }

        }
    </script>

</body>
</html>

Page2.php

<?php
    $var = $_POST['sendpost']; //This line is not in use
    echo "return";
?>

此代码运行良好! Page1将值valuetest发送到page2,而无需刷新页面。 echo的{​​{1}}返回值page2return,并将其插入page1中。到目前为止,一切都很好。我希望代替div="receive"接收值,而是触发函数div="receive"或任何其他允许我设置myfunction2(css)样式的方法。

简而言之:page1的返回仅应用于调用page2的方法。

1 个答案:

答案 0 :(得分:0)

您可以仅将函数作为成功回调进行传递。

<script type="text/javascript">
        function myfunction() {
          $.ajax({
            type: "POST",
            url: "page2.php",
            data: {
              sendpost: $('#idinput').val()
            },
            success: myfunction2
          });

         function myfunction2(){

         }

        }
    </script>

如果要返回一个触发函数的字符串,则可以返回该函数的名称,并将其传递给评估字符串的eval()函数。

// In your php
<?php
    $var = $_POST['sendpost']; //This line is not in use
    echo "myfunction2()";

// In your js

success: function(data) {
    eval(data); // Call the function returned by your PHP
}