使用 AJAX 将数据发送到 PHP 文件,并使用该数据运行 PHP 脚本


Sending data with AJAX to a PHP file and using that data to run a PHP script

我目前正在尝试使用 PHP 和 AJAX 进行实时表单验证。所以基本上 - 我需要通过 AJAX 将字段的值发送到 PHP 脚本(我可以这样做),然后我需要在该 PHP 文件中运行一个函数,其中包含我发送的数据。我该怎么做?

JQuery:

$.ajax({
  type: 'POST',
  url: 'validate.php',
  data: 'user=' + t.value,   //(t.value = this.value),
  cache: false,
  success: function(data) {
    someId.html(data);
  }
});

验证.php:

现在我需要使用我在这个函数中发送的"user"值,我该怎么做?

function check_user($user) {
  //process the data
}

如果我不使用函数,只是在验证中使用原始 php.php则发送数据并执行其中的代码,并且一切都按照我喜欢的方式工作,但是如果我添加每个功能,我希望事情变得非常混乱,所以我更喜欢使用单独的函数。

我删除了许多不相关的代码,以使其简短。

1)这看起来不太好

data: 'user=' + t.value,   //(t.value = this.value),

这很好

data: {user: t.value},  

2) 使用 $_POST

function check_user($user) {
    //process the data
}
check_user($_POST['user'])

您只需要在文件中调用该函数即可。

if(isset($_REQUEST['user'])){
    check_user($_REQUEST['user']);
}

在验证中.php您将收到经典的 POST 请求。您可以根据要测试的变量轻松调用该函数,如下所示:

<?php
if (isset($_POST['user'])) {
    $result = check_user($_POST['user']);
}
elseif (isset($_POST['email'])) {
    $result = check_email($_POST['email']);
}
elseif (...) {
    // ...
}
// returning validation result as JSON
echo json_encode(array("result" => $result));
exit();
function check_user($user) {
   //process the data
   return true; // or flase
}
function check_email($email) {
   //process the data
   return true; // or false
}
// ...
?>

数据在$_POST全局变量中发送。您可以在调用 check_user 函数时访问它:

check_user($_POST['user']);

但是,如果您这样做,请记住检查字段值,其中是否没有发送任何恶意内容。

这是我的做法

Jquery 请求

$.ajax({
            type: 'POST',
            url: "ajax/transferstation-lookup.php",
            data: {
                'supplier': $("select#usedsupplier").val(),
                'csl': $("#csl").val()
            },
            success: function(data){
                if (data["queryresult"]==true) {
                    //add returned html to page
                    $("#destinationtd").html(data["returnedhtml"]);
                } else {
                    jAlert('No waste destinations found for this supplier please select a different supplier', 'NO WASTE DESTINATIONS FOR SUPPLIER', function(result){ return false; });
                }
            },
            dataType: 'json'
        });

PHP页面只需 2 个输入

$supplier = mysqli_real_escape_string($db->mysqli,$_POST["supplier"]);
$clientservicelevel = mysqli_real_escape_string($db->mysqli,$_POST["csl"]);

通过查询运行它们。 现在就我而言,我只是返回存储在 json 数组中的原始 html,并带有一个检查标志,表示查询已成功或失败,如下所示

$messages = array("queryresult"=>true,"returnedhtml"=>$html);
echo json_encode($messages); //encode and send message back to javascript

如果你回顾一下我最初的javascript,你会发现我对queryresult有条件,然后只是把原始html吐回div,你可以用它做任何你需要的事情。