如何将变量从 jquery ajax 传递给 PHP MVC

how to pass variable from jquery ajax to php mvc

本文关键字:PHP MVC ajax jquery 变量      更新时间:2023-09-26

我正在使用php-mvc并使用ajax添加搜索功能。我将如何从input传递值以建模和查询值。我试图getAllUsersProfiles方法中添加$_GET['searchData']但它没有得到值。

.HTML:

<input type="text" id="searchData" placeholder="search name here..." />
...
<!--where I want to output the search result -->      
<tbody id="account_results"></tbody>

.JS:

$("#searchData").keyup(function(){
  var searchValue = $.trim($(this).val());
  if(searchValue !== ''){
        $.get("<?php echo URL; ?>admin/index/", function(returnData){
          if(!returnData)
            $("#account_results").html("<p>No record(s) found.</p>");
          else
            $("#account_results").html(returnData);
        });
  }
});

PHP模型:

public function getAllUsersProfiles()
{
    $sql = "SELECT id, username, email, active, firstname, lastname
            FROM users";
    if(isset($_GET['searchData'])) {
        $sql .= " WHERE CONCAT(TRIM(firstname), ' ', TRIM(lastname))
                        LIKE '%:searchData%'";
        $sth = $this->db->prepare($sql);
    }
    else
      //if search input is not set, output all of the list.
      $sth = $this->db->prepare($sql);
      $sth->execute();
      $all_users_profiles = array();
      foreach ($sth->fetchAll() as $user) {
        //code here..
      }
     return $users;
}

PHP 控制器:

class Admin extends Controller
{
function __construct()
{
    parent::__construct();
}
function index()
{
    $admin_model = $this->loadModel('Admin');
    $this->view->users = $admin_model->getAllUsersProfiles();
    $this->view->render('admin/index');
}

您的 PHP 代码不会获取 searchData 值,因为您没有随 GET 请求一起发送它。在您的 JS 部分中尝试一下:

$("#searchData").keyup(function(){
  var searchValue = $.trim($(this).val()), url = '<?php echo URL; ?>/admin/index/?searchData=' + searchValue;
  if(searchValue !== ''){
        $.get(url, function(returnData){
          if(!returnData)
            $("#account_results").html("<p>No record(s) found.</p>");
          else
            $("#account_results").html(returnData);
        });
  }
});

然后你可以在PHP中用$_GET['searchData']获取值