将变量从 AJAX 传递到 PHP Web API


Passing variable from AJAX to PHP web API

我在 php 中有一个简单的 web api,它调用索引.php文件中一个名为 getData 的函数,如下所示:

索引.php

<?
session_start();
require("lib.php");
require("api.php");
header("Content-Type: application/json");
    getData($name);
exit();
?>

getData 函数位于 API.php 文件中,如下所示:

接口.php

<?
function getData($name) {
$result = query("select * FROM table where name = $name");
    print json_encode($result);
}
?>

我想在我的 JavaScript 中使用 AJAX 检索 json,如下所示:

$(document).ready(function () {
    var url = 'webAPI/index.php';
    var j = [];
    $.ajax({
           type: 'GET',
           url: url,
           dataType: 'json',
           success: function(data) { j = data;},
           async: false
           });

如果没有传递$name变量,这非常有效,但我需要将$name变量从 AJAX 传递到 index.php 文件以获得正确的 sql 结果。我尝试将 AJAX 制作为帖子,但无济于事。

GET AJAX 请求发送的变量可从超全局$_GET获得。例如,如果这是你的jQuery代码:

 $.ajax({
       type: 'GET',
       url: url,
       dataType: 'json',
       data: { name:"something" }, // you can replace name with whatever you need
       success: function(data) { j = data;},
       async: false
 });

然后您可以使用 $_GET["name"] 访问 name 变量。因此,您可以将从客户端发送的数据与getData($_GET["name"]);

一起使用

另外,请确保您使用正确的函数来访问您的数据库,例如 MySQLi for PHP。