Home > Article > Backend Development > thinkphp echo return returns json data problem
Today I have been tinkering with a jquery autocomplete plug-in
I used ajax to get the drop-down data from the background, and then it was a pain in the ass
First of all, let me explain that I use the thinkphp framework
First of all, I must return the json data
Then I willreturn json_encode($end,JSON_UNESCAPED_UNICODE);
The result is that the front-end js plug-in keeps reporting errors, which probably means that the returned json data is illegal
Then after tinkering with it for a long time, I try to use echo json_encode($end,JSON_UNESCAPED_UNICODE);
The result It works, I’m still puzzled. Can someone please explain? The things are exactly the same, but there’s an echo and a return. How can there be a difference
Today I have been tinkering with a jquery autocomplete plug-in
I used ajax to get the drop-down data from the background, and then it was a pain in the ass
First of all, let me explain that I use the thinkphp framework
First of all, I must return the json data
Then I willreturn json_encode($end,JSON_UNESCAPED_UNICODE);
The result is that the front-end js plug-in keeps reporting errors, which probably means that the returned json data is illegal
Then after tinkering with it for a long time, I try to use echo json_encode($end,JSON_UNESCAPED_UNICODE);
The result It works, I’m still puzzled. Can someone please explain? The things are exactly the same, but there’s an echo and a return. How can there be a difference
The js callback requires a value, and php must only output a json string before it can receive it.
This is the http protocol, the concept of request sending and response receiving. There must be a value in the content returned by response. It can only be obtained by ajax.
The statement that PHP outputs the json string as it is is echo and the function is exit()die()
As for the return of the controller layer in thinkphp. Just returned to thinkphp core controller class. Finally, if the controller does not output any output, the response content will be empty.
SF has had a similar question before: the difference between echo and return
Let me say it again:
return
is to return results to the PHP program.echo
is the response of Ajax.
I’m really drunk. The original poster saw an error in the front-end js, couldn’t he take a look at the return value of ajax? Isn't it obvious what the problem is?
The correct approach should be
<code class="php">exit(json_encode($end,JSON_UNESCAPED_UNICODE));</code>
return
is returned in function. echo
is output to the page.
TP has a $this->ajaxReturn(); method, which can be used directly.