gpt4 book ai didi

javascript - 如何将变量从 jquery ajax 传递到 php mvc

转载 作者:行者123 更新时间:2023-12-03 11:16:09 25 4
gpt4 key购买 nike

我正在使用php-mvc并使用 ajax 添加搜索功能。如何将值从输入传递到模型并查询该值。我尝试在 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 Controller :

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'] 获取值

关于javascript - 如何将变量从 jquery ajax 传递到 php mvc,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27338888/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com