php中的return/echo json_encode有什么区别

 百变精灵110 发布于 2023-02-12 18:23

也许这是一个简单而愚蠢的问题.

我们知道,echo 只需打印变量,然后在php函数return中将函数返回给函数调用者.

我注意到有人在使用echo json_encode其他人时使用return json_encode,

我将一些内容返回给jquery,并使用echo/return都可以.

但是当我发现几乎所有人都在使用时echo json_encode,为什么?

谢谢.

1 个回答
  • return在使用ajax的情况下不会给出任何响应,因为它echo会给你响应.如果你正在使用服务器端脚本,可能你不需要回应它.而不是它你可以使用return.

    查看此示例以及调用函数的方式

    function  myFun($value){
      return 'This is the value '.$value;
    }
    
    echo myFun(10);//Output This is the value 10
    myFun(10);//Will not give you any output
    
    function  myFun($value){
      echo 'This is the value '.$value;
    }
    
    myFun(10);//Output This is the value 10
    echo myFun(10);//Output This is the value 10
    

    在ajax的情况下

    $.ajax({
            url     :   'mypage.php',
            type    :   "POST",
            success :   function(res){
              alert(res);
            }
     });
    

    在mypage.php中

     echo 'Hello';//This will send Hello to the client which is the response
    

    return 'Hello';//Will not send anything.So you wont get any response
    

    2023-02-12 18:25 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有