简体   繁体   English

如何使用jquery加载在php文件中调用函数?

[英]How to call a function in a php file using jquery load?

I am trying to display the data i retrieve from the database but it is not being displayed. 我正在尝试显示从数据库中检索到的数据,但未显示。 I have a function in the file getComments.php called "getComments(page)" page is just a integer parameter to choose that database. 我在文件getComments.php中有一个名为“ getComments(page)”的函数,页面只是选择该数据库的整数参数。 and as you can see that i need to call this function to print the users comments. 如您所见,我需要调用此函数来打印用户评论。 I am trying to use "load" but it is not being successful i just want to call this function to load the comments on the page. 我正在尝试使用“加载”,但未成功,我只想调用此函数以加载页面上的评论。 thank you in advance. 先感谢您。

<?php

use TastyRecipes\Controller\SessionManager;
use TastyRecipes\Util\Util;

require_once '../../classes/TastyRecipes/Util/Util.php';
Util::init();

function getComments($page){
   echo "<br><br>";
   $controller = SessionManager::getController();
   $controller->getComments($page);
   SessionManager::setController($controller);
}

and in my web page where i want to display it using java script, i tried the following 在我想使用Java脚本显示的网页中,我尝试了以下操作

<div class="page" id="comments">
  <p class="style">Comments</p>
  <button class="btn" id="load-comments">See Previous Comments</button><br> 
  <br><br>

  <?php
    if(isset($_SESSION['u_id'])){
       echo "  <input type='hidden' id='uid' value = '".$_SESSION['u_uid']."'>
          <input type='hidden' id='date' value = '".date('Y-m-d H:i:s')."'>
          <textarea id='message'></textarea><br>
          <button class = 'btn' type = 'submit' id = 'submitCom'>Comment</button>";
    }
    else{
      echo "<p>Please log in to comment</p>";
    }
   ?>
</div><br>
<script>
  $(document).ready(function(){
    $("#load-comments").click(function(){
     document.getElementById('#comments').innerHTML = 
    $("#comments").load("../extras/getComments.php", getComments(1));
    });
  });
</script>

Just change your click handler to this: 只需将您的click处理程序更改为:

$("#load-comments").click(function(){
    $("#comments").load("../extras/getComments.php", { page: 1 }); //i also added where the elements are loaded
});

and in getComments.php (if practical, otherwise you might need to create a new PHP file which calls the getComments() function and call that from the click handler instead) add something like: 并在getComments.php (如果可行,否则,您可能需要创建一个新的PHP文件,该文件调用getComments()函数,然后从点击处理程序中调用它),添加以下内容:

if (isset($_POST['page'])) {
    getComments($_POST['page']);
    // do any other necessary stuff
    exit;
}

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

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