也许这是一个简单而愚蠢的问题。
众所周知,echo
只是打印出变量,并在 php 函数中return
statnds 向函数调用者返回一些内容。
我注意到有人使用echo json_encode
而其他人使用return json_encode
,
我向jquery返回一些东西,使用echo/return都可以。
但是当我发现几乎每个人都使用echo json_encode
,为什么呢?
谢谢。
在使用
ajax 的情况下,return
不会给出任何响应,因为echo
会给你响应。如果您仅使用服务器端脚本,则可能不需要回显它。代替它,您可以使用返回。
看看这个例子以及调用函数的方式
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({
url : 'mypage.php',
type : "POST",
success : function(res){
alert(res);
}
});
在我的页面中.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
在标准PHP代码中,echo
的输出由Web服务器捕获并作为响应的一部分返回。
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(...)
时,这意味着调用函数将在数据输出到服务器之前对数据执行某些操作。
>return
将简单地返回变量而不回显它,而echo
在调用它时会回显它。如果您使用的是 AJAX,则最好使用echo
这取决于你正在使用的php框架的性质
如果你使用的是 ajax 并且你的框架自己做标准输出,那么你可以使用 return,否则你必须自己回显它