【问题标题】:PHP JSON not returning value from php functionPHP JSON没有从php函数返回值
【发布时间】:2021-02-17 19:24:58
【问题描述】:

假设我有以下功能。 alert_danger 返回红色框内的错误信息。 check_empty 检查从表单发布的值是否为空。

function alert_danger($msg){
  $alert = "<div class='alert alert-danger' id='responseBox'>".$msg."</div>";
  return $alert;
}

function checkEmpty($postValue, $msg){
  if($postValue == null){
    echo alert_danger($msg);
    exit();
  }
}

现在,当我想使用 JSON 返回函数值时,它返回的不是相同的值。出现以下错误:

// It returns this
$msg = alert_danger("Ah! Hello Adventurer, and welcome to the town of Honeywood!");
echo json_encode(array('status' => $msg));

// But it does not returns this
$msg = checkEmpty($state, "Ah! Hello Adventurer, and welcome to the town of Honeywood!");
echo json_encode(array('status' => $msg));

这里似乎有什么问题?

如果需要,这是我的 jQuery!

$(".action").click(function() {
  var form = $(this).closest("form");
  var type = form.find(".type").val();
  var dataString = form.serialize();
  var btnValue = $(".action").html();
  var btnElement = $(".action");
  var url = form.attr("action");
  $.ajax({
    type: "POST",
    dataType : "json",
    url: url,
    data: dataString,
    cache: true,
    beforeSend: function(){
      $('.message').hide();
      $(".overlay").show();
      $(".wickedpicker").hide();
      btnElement.html('Please wait...');
    },
    success: function(json){
      $('.message').html(json.status).fadeIn();
      // $('#content').html(json.result).fadeIn();
      $(".overlay").hide();
      $("html, body").animate({ scrollTop: $(".message").offset().top }, "slow");
      btnElement.html(btnValue);
      if(type == 'admin'){
        if($('.message').find('#responseBox').hasClass('alert-success')){
          setTimeout(function(){
            $(".overlay").hide();
            window.location.replace("dashboard.php");
          }, 1000);
        }
      }
    }
  });
  return false;
});

【问题讨论】:

  • alert_danger 函数在哪里?你怎么打电话给checkEmpty?但是checkEmpty 没有返回任何值......所以分配$msg = checkEmpty 是没有意义的
  • alert_danger 是否返回值?
  • 你的函数没有return任何内容。这将使$msg 成为null
  • @ProfessorAbronsius 我已经更新了这个问题。请检查。我以为我不需要在那里提到 alert_danger() 函数所以我没有,但既然你要求它,我已经更新了它。
  • @Twisty 我的函数确实返回了一个值。当我不使用 JSON 时,一切都运行良好。但如果我使用 JSON,那么它不会返回任何值。

标签: php jquery json ajax function


【解决方案1】:

考虑以下内容。

PHP

<?php
function checkEmpty($postValue, $msg){
  return $postValue == null ? array("status" => "error", "message" => "Empty Value") : array("status" => $postValue, "message" => $message);
}

header('Content-Type: application/json');
echo json_encode(checkEmpty($state, "Ah! Hello Adventurer, and welcome to the town of Honeywood!"););
?>

JavaScript

function redirectTo(url, time) {
  if (!url) {
    return false;
  }
  time = time != undefined ? time : 0;
  setTimeout(function() {
    window.location.href = url;
  }, time);
}

$(".action").click(function() {
  $(this).closest("form").submit();
});

$("form").submit(function(event) {
  event.preventDefault();
  var type = $(this).find(".type").val();
  var dataString = $(this).serialize();
  var btnValue = $(".action").html();
  var btnElement = $(".action");
  var url = $(this).attr("action");
  $.ajax({
    type: "POST",
    dataType: "json",
    url: url,
    data: dataString,
    cache: true,
    beforeSend: function() {
      $('.message').hide();
      $(".overlay").show();
      $(".wickedpicker").hide();
      btnElement.html('Please wait...');
    },
    success: function(json) {
      if (json.status == "error") {
        $(".message").html("<div class='alert alert-danger error'>" + json.message + "</div>").fadeIn();
      } else {
        $('.message').html("<div class='alert alert-danger'>" + json.message + "</div>").fadeIn();
        $("html, body").animate({
          scrollTop: $(".message").offset().top
        }, "slow");
        btnElement.html(btnValue);
        if (type == 'admin') {
          if ($('.message').find('#responseBox').hasClass('alert-success')) {
            redirectTo("dashboard.php", 1000);
          }
        }
      }
    }
  });
  return false;
});

通常,使用语言 X 生成语言 Y 的代码是不好的做法。尝试通过使数据成为其唯一接口来解耦这两种语言——不要混合代码。

https://softwareengineering.stackexchange.com/questions/126671/is-it-considered-bad-practice-to-have-php-in-your-javascript

您必须小心不要混淆echoreturn,它们做的事情非常不同。

https://www.php.net/manual/en/function.echo.php

https://www.php.net/manual/en/function.return.php

由于您将 JSON 数据传回给 AJAX 调用,因此我建议您将 HTML 包装在回调中,而不是将其发送回 JSON 中。

【讨论】:

    【解决方案2】:

    我认为你应该看看你的成功函数。我认为它通常在页面加载之前运行。因此,您在其中引用的 html 可能都不存在。所以把它移到这样的函数中:

    success: function(json) {
    doSomething();
    }
    
    function doSomething(json){
        $( document ).ready(function() {
        console.log('page has loaded now modify your html with jquery'+json);
        }
    }
    

    【讨论】:

    • 显然我们现在都使用简码: $(function() { console.log( "ready!" ); });
    猜你喜欢
    • 1970-01-01
    • 2014-07-05
    • 1970-01-01
    • 2017-01-08
    • 1970-01-01
    • 2013-08-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多