Home > Article > Backend Development > javascript - How can a php function be called by ajax and php itself?
That is, if the request is sent by ajax, then ajax receives the echo data;
If it is called internally and receives return data, can you write an if statement to determine who sent it? Use echo or return?
How to write this if statement?
That is, if the request is sent by ajax, then ajax receives the echo data;
If it is called internally and receives return data, can you write an if statement to determine who sent it? Use echo or return?
How to write this if statement?
Ajax request has one more "x-requested-with XMLHttpRequest
" than the traditional request header. You can use it. If request.getHeader("x-requested-with"); is null, it is traditional synchronization. The request is an XMLHttpRequest, or an Ajax asynchronous request.
But the above is not completely accurate. You can add a data type format you want to return when requesting
When you have this need, you should consider whether there is a problem with your code structure.
It is possible, but it is not recommended.
You can judge $_GET
or $_POST
echo and return are not written in the same function.
There is IS_AJAX in tp, you can see how it is written.
If you need it, you should add a field to your returned result set to indicate the type, but there is no need for this during normal development. I don't know why you need to distinguish between echo and return?
Generally, you don’t use a function that both echoes and returns.
You can do this
<code>function a(){ return $result; } function 4AJAX(){ echo a(); } </code>
If you want to call internally, use a(), if you want AJAX, use 4AJAX().