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

时间:2013-12-05 06:00:18

标签: php return echo json

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

正如我们所知,echo只是打印变量,并在php函数return中为函数调用者返回一些内容。

我注意到有人使用echo json_encode而其他人使用return json_encode

我将某些内容返回给jquery,并且使用echo / return 都正常

但当我发现几乎每个人都使用echo json_encode时,为什么?

感谢。

4 个答案:

答案 0 :(得分:7)

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

答案 1 :(得分:1)

在标准PHP代码中,echo的输出由网络服务器捕获并作为响应的一部分返回。

return只是将值返回到父函数。父函数可以使用包含echo的返回数据执行任何操作。

考虑:

function return_some_text(){
   return 'this text is returned';
}

function echo_some_text(){
   echo 'this text is echoed';
}

//does nothing
return_some_text(); 

//'this text is echoed' appears in the response
echo_some_text();   

//'this text is returned' appears in the response because the return value is echoed.
echo return_some_text(); 

请记住,函数的返回值可以以调用者认为合适的任何方式使用。如果来电者认为合适,这包括echo

当你看到return json_encode(...)时,这意味着调用函数在输出到服务器之前将对数据执行某些操作。

答案 2 :(得分:0)

return只会返回变量而不回显变量,而echo会在调用变量时将其回显。如果您使用的是AJAX,最好使用echo

答案 3 :(得分:0)

这取决于你正在使用的php框架的性质

如果你正在使用ajax并且你的框架自己进行标准输出,那么你可以使用return,否则你必须自己回复它