William Jiang

JavaScript,PHP,Node,Perl,LAMP Web Developer – http://williamjxj.com; https://github.com/williamjxj?tab=repositories

Ajax: More processings in an individual Ajax request

I want to send more than 1 ajax requests within a button click. The following codes illustrates when clicking the button ‘1 or 3 processing when click?’, 3 async Ajax requests are sent to server at the same time, and the responses will refresh different divs in the webpage.

  • the first processing uses jQuery.load(), to refresh <div id=”div1″>1</div>
  • the second processing uses jQuery.get(), to refresh <div id=”div2″>1</div>
  • the first processing uses jQuery’s.post(), to refresh <div id=”div3″>1</div>

For simplifying, the 3 requests go to same URL: $_SERVER[‘PHP_SELF’]/test_multi_ajax.html. Of course, the URL can be different.

<html><head>
<script language="javascript" type="text/javascript" src="jquery-1.5.1.min.js"></script>
</head>
<body>
<div id="div1">1</div>
<div id="div2">2</div>
<div id="div3">3</div>
<input type="button" id="loading" value="1 or 3 processing when click?" />
<script language="javascript" type="text/javascript">
$('#loading').click(function() {
 $('#div1').load('test_multi_ajax.html #container');
 $.get('test_multi_ajax.html', function(data) {
  $('#div2').html(data);
 });
 $.post('test_multi_ajax.html', function(data) {
  $('#div3').html(data);
 });
 return false;
});
</script>
</body>
</html>

The script ‘test_multi_ajax.html’ is list below (it can be any php or html script):

<div> this is the First test. </div>
<div id="container"> only container is included. </div>
<div> this is the LAST test. </div>

The behaviors behind the click is, the jQUery codes fork 3 processes to deal with 3 different ajax processings: each of them runs independently, no associated with each other. And the responses will present in different parts of the webpage, here is 3 divs: ‘div1’, ‘div2’, ‘div3’.

It is powerful enough: many online real-time searching system (e.g: airplan tickets) should use this way to get information from different repositories when user clicks ‘search tickets’ button.
On the other side, for a greedy script, it can eat huge bandwidth and memory if it forks many processes to do the network occupying.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: