PHP中return / echo json_encode之间有什么区别 [英] what's the difference between return/echo json_encode in php
问题描述
也许这是一个简单而愚蠢的问题。
我们知道, echo
只是将变量打印出来,并在php函数 return
状态中将某些内容返回给函数调用者。
我注意到有人在使用 echo json_encode
,而其他使用返回json_encode
我返回了一些内容到jquery,并使用echo / return都可以。都可以。
但是当我发现几乎每个人都在使用 echo json_encode
时,为什么?
谢谢。
返回
不会在使用ajax的情况下给出任何响应,例如 echo
会给您响应。如果您使用服务器端脚本,则可能不需要回显它。您可以使用return。
请看此示例以及调用函数的方式
function myFun($ value){
return'这是值'。$ value;
}
echo myFun(10); //输出这是值10
myFun(10); //不会给你任何输出
函数myFun($ value){
echo'这是值'。$ value;
}
myFun(10); //输出这是值10
echo myFun(10); //输出这是值10
$ a $ b > $。ajax({
url:'mypage.php',
type: POST,
成功:function(res){
alert(res);
}
});
在mypage.php中
echo'Hello'; //这会将Hello发送给客户端,即响应
但是
返回 Hello; //将不会发送任何内容。因此您将不会得到任何响应
maybe this is a simple and stupid question.
As we know, echo
just print the variable out, and in a php function return
statnds for return something to the function invoker.
I notice someone use echo json_encode
while others using return json_encode
,
I return something to jquery, and using echo/return are both ok.
But when I find that almost everyone using echo json_encode
, and why ?
Thanks.
return
will not give any response in case of using ajax where as echo
will give you the response.If you are using server side scripting only the probably you dont need to echo it.Instead of it you can use return.
Look at this example and the way which the functions are called
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
In case of ajax
$.ajax({
url : 'mypage.php',
type : "POST",
success : function(res){
alert(res);
}
});
In mypage.php
echo 'Hello';//This will send Hello to the client which is the response
but
return 'Hello';//Will not send anything.So you wont get any response
这篇关于PHP中return / echo json_encode之间有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!