从 ajax 函数从数据库中检索数据值

Retrieving data value from database from ajax function

本文关键字:数据 检索 数据库 ajax 函数      更新时间:2023-09-26

我有一个ajax函数,它可以从我的数据库中检索数据并将其显示在我的文本框中。我正在使用JQuery表单插件来稍微缩短ajax进程。现在我想做的是从我从 ajax 函数调用的 php 脚本中获取数据。

表单标记为:

<form action="searchFunction.php" method="post" id="searchForm">
  <input type="text" name="searchStudent" id="searchStudent" class="searchTextbox" />
  <input type="submit" name="Search" id="Search" value="Search" class="searchButton" />
</form>

searchFunction.php中的服务器代码

$cardid = $_POST['searchStudent'] ;
$cardid = mysql_real_escape_string($cardid);
$sql = mysql_query("SELECT * FROM `users` WHERE `card_id` = '$cardid'") or trigger_error(mysql_error().$sql);
$row = mysql_fetch_assoc($sql);
return $row;

处理 php 的 ajax 脚本是

$(document).ready(function() {
  $('#searchForm').ajaxForm({
    dataType: 'json',
    success: processSearch
  });
});
function processSearch(data) {
  alert(data['username']); //Am I doing it right here?
}

在 PHP 中,如果我想调用数据,我只需为数据库创建一个函数,例如echo $row['username']它。但是我如何使用 ajax 执行此操作?我对此相当陌生,所以,请解释一下过程。

$('#Search').click(function (e) {
    e.preventDefault(); // <------------------ stop default behaviour of button
    var element = this;    
    $.ajax({
        url: "/<SolutionName>/<MethodName>",
        type: "POST",
        data: JSON.stringify({ 'Options': someData}),
        dataType: "json",
        traditional: true,
        contentType: "application/json; charset=utf-8",
        error: function () {
                    alert('Unable to load feed, Incorrect path or invalid feed');
                },
                 success: processSearch,
    });
});
 function processSearch(data) {
var username= ($(data).find('#username'));

}

更改输入类型"提交到"按钮。提交将触发表单中的操作,因此表单将被重新加载。如果您正在执行 ajax 调用,请将其更改为按钮。

一切似乎都很好,除了这一点——

function processSearch(data) {
   alert(data['username']); //Am I doing it right here?
}

您需要将其更改为 -

function processSearch(data) {
   // data is a JSON object. Need to access it with dot notation
   alert(data.username);
}

更新

您还需要从 PHP 文件返回 JSON 响应。像——

// Set the Content Type to JSON
header('Content-Type: application/json');
$data = [
    "key" => "value"
];
return json_encode($data);

在您的情况下,您可以像这样直接对$row进行编码 -

return json_encode($row);