Home >Backend Development >PHP Tutorial >Asynchronous request to PHP server without returning data? (Attached is the solution)
Recently discovered a ajax
asynchronous request problem, use $.post
, $.get
, $.ajax
When requesting the PHP server, data cannot be returned asynchronously.
After many tests, we discovered:
– Different browsers, request different domain names - no blocking: no experiment required
– Different browsers, request the same domain name - Non-blocking: session_id()
Returns different
– The same browser requests different domain names - Non-blocking: session_id
Returns different
– The same browser requests the same domain name -Blocking: session_id()
Returns the same
Found the problem:
1 Close XDEBUG
2 SESSION
Lock
3 Clear the output buffer
1 CloseXDEBUG
XDEBUG
is real-time debugging. When debugging, it will keep FPM
to ensure the thread is working to avoid data pollution.
The typical test method is to open another browser and access the site when debugging using XDEBUG
. The site is inaccessible at this time.
This has a significant impact on parallel responses, i.e. even if the frontend sends multiple requests, it is controlled by XDEBUG
and can only respond to one at a time.
Also, since
XDEBUG will still open automatically.
2
SESSION
Lock
Use session_write_close() to close the write lock of
SESSION, which is suitable for
SESSION is saved as
File. Not required if
SESSION is saved in
Redis.
3 Clear the output buffer
Using
may not close the SESSION lock immediately, so add it before this method :
ob_end_flush(). Let
session_write_close() take effect immediately.
4 Example
There is an example below. When the [Submit] button is clicked, the front end will send two requests to the backend server.
get request, which is requested every 1 second. One is the
post
request, which is sent once at the beginning and then waits for the corresponding end. Look at the HTML code
<form> <input type="submit" value="提交" /> </form> <script src="//cdn.bootcss.com/jquery/3.1.1/jquery.min.js"></script> <script type="text/javascript"> $('form').on('submit', function(e) { e.preventDefault(); // 每隔一秒请求一次服务器 var id = setInterval(function() { $.get( 'save.php?action=get', {}, function(data) { console.log(data); }, 'json' ); }, 1000); $.post( 'save.php?action=post', {}, function(data) { console.log(data); // 停止定时循环 clearInterval(id); }, 'json' ); }); </script>
php code
cf44e1b56b3cc8a68161c85bcd1685b9 $_SESSION['time']]); exit();}if ($action == 'get') { echo json_encode([session_id() => $_SESSION['time']]); exit();}
Recommended study: "
PHP Video Tutorial" ##
The above is the detailed content of Asynchronous request to PHP server without returning data? (Attached is the solution). For more information, please follow other related articles on the PHP Chinese website!