PHP函数的返回看起来如何对AJAX和PHP有效



我得到了一个输入字段。一些AJAX请求正在动态检查用户输入。然后,用户被告知他/她的输入是否正常。

提交后,必须再次检查输入是否具有与AJAX之前检查的相同的特性(在JavaScript被禁用的情况下)。

AJAX异步使用"check.php"。

<?php
include 'foo.php';
$input= $_POST['input'];
checkSomethingElse(testSomething($input));
?>

然后我得到了一个"submit.php"文件,它在提交时被调用。它检查输入,然后将输入写入数据库。

<?php
    include 'foo.php';
    $input= $_POST['input'];
    checkSomethingElse(testSomething($input));
foo(){
//write input into Database}
?>

"foo.php"看起来像这个

<?php
function testSomething(){
//do something
}
function checkSomethingElse(){
//test...
echo value   // e.g. echo "true"
return value // e.g. return true
?>

(例如验证和消毒输入和其他检查)

为了AJAX/JS/JQuery使用返回值,它是通过"echo"返回的。

为了让PHP使用返回值,它是通过"return"返回的。

在AJAX请求的情况下,一切都很好,因为它忽略了"return",只使用了"echo"。在PHP的情况下,它使用"返回值"并打印出"回声值"。

所以问题是:这种结构在逻辑上和功能上都可以吗?当用户不使用JavaScript时,我如何修复这段代码,使其通过"echo"吐出一个字符串?

谢谢。

首先,我看到的第一个问题是,您在返回后调用echo。。。这将永远不会发生,因为一旦函数返回,它的执行就会停止。

我建议您只生成返回值的函数,然后确定之后是否需要回显它。。。

<?php
  function some_function() {
    return "value";
  }
  $value = some_function();
  if (isset($_POST["returnajax"])) {
    echo $value;
  }
?>

正如@rmvanda所建议的那样,如果您正在处理期望json的AJAX请求,那么json_encode可能对您有用。在这种情况下,它可能看起来像这样。。。

function some_function() {
  return "value";
}
function some_other_function() {
  return "another_value";
}
$values = array();
$values[] = some_function();
$values[] = some_other_function();
if (isset($_POST["returnajax"])) {
  header("Content-Type: application/json");
  echo json_encode($values);
}

产生的回波看起来像这样:

["value","another_value"]

不幸的是,您可能会发现jquery不喜欢格式不好的json。我通常做的是:

if (isset($_POST["returnajax"])) {
  header("Content-Type: application/json");
  echo json_encode(array("values"=>$values));
}

这将导致:

{"values":["value","another_value"]}

将显示逻辑与验证逻辑分离。

例如:

// validation functions
function testSomthing(){
    //test...
    return $value; // e.g. return true
}
function checkSomethingElse(){
    //test...
    return $value; // e.g. return true
}
// calling logic in check.php
include 'foo.php';
$result = false;
if (!empty($_POST['input']) {
    $input= $_POST['input'];
    $result = checkSomethingElse(testSomething($input));
}
$return = new stdClass();
$return->result = $result;
header("Content-Type: application/json");
echo json_encode($return);

注意:从您的示例中不清楚为什么要嵌套验证函数调用(即checkSomethingElse(testSomething($input)))。我不认为它会以这种方式工作(因为你会将true/false结果传递给外部函数调用),但我在这里展示的代码和你一样,因为我当然没有完整的函数用法来提供替代方案。

您可以检查变量$_SERVER['HTTP_X_REQUESTED_WITH']

if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
    /* special ajax here echo for example*/
}
else {
  /* Not AJAX use return*/
}

最新更新