开发者

How to call multiple AJAX functions (to PHP) without repeating code

I have a little script which uses AJAX and PHP to display an image. You can see below that if I call the function mom() it looks in the PHP file index.php?i=mom and displays the image I'm looking for.

But I need the javascript to be lighter as I have 30 images and for each one I have to modify and copy the script below. Is there not a simpler way to have the functions be different and still call a different page?

<script type="text/javascript">
function mom()
{
    var xmlHttp = getXMLHttp();
    xmlHttp.onreadystatechange = function()
    {
        if(xmlHttp.readyState == 4)
        {
            HandleResponse(xmlHttp.responseText);
        }
    }
    xmlHttp.o开发者_如何学Pythonpen("GET", "index.php?i=mom", true); 
    xmlHttp.send(null);
}
function HandleResponse(response)
{
  document.getElementById('mom').innerHTML = response;
}
</script>

My Trigger is this

<a href="#" onclick='mom();' />Mom</a>
<div id='mom'></div>


You could modify your function so it takes a parameter :

// The function receives the value it should pass to the server
function my_func(param)
{
  var xmlHttp = getXMLHttp();
  xmlHttp.onreadystatechange = function()
  {
    if(xmlHttp.readyState == 4)
    {
      // Pass the received value to the handler
      HandleResponse(param, xmlHttp.responseText);
    }
  }
  // Send to the server the value that was passed as a parameter
  xmlHttp.open("GET", "index.php?i=" + param, true); 
  xmlHttp.send(null);
}


And, of course, use that parameter in the second function :

function HandleResponse(param, response)
{
  // The handler gets the param too -- and, so, knows where to inject the response
  document.getElementById(param).innerHTML = response;
}


And modify your HTML so the function is called with the right parameter :

<!-- for this first call, you'll want the function to work on 'mom' -->
<a href="#" onclick="my_func('mom');" />Mom</a>
<div id='mom'></div>

<!-- for this secondcall, you'll want the function to work on 'blah' -->    
<a href="#" onclick="my_func('blah');" />Blah</a>
<div id='blah'></div>


This should work (if I understand correctly)

<script type="text/javascript">
function func(imgName)
{
  var xmlHttp = getXMLHttp();
  xmlHttp.onreadystatechange = function()
  {
    if(xmlHttp.readyState == 4)
    {
      document.getElementById(imgName).innerHTML = 
    }
  }
  xmlHttp.open("GET", "index.php?i=mom", true); 
  xmlHttp.send(null);
}
</script>


MARTIN's solution will work perfectly.

By the way you should use some javascript framework for Ajax handling like jQuery.

It will make your life easy.

If you are having light weight images you preload the images on your page.


I solved this by making an array of in your case xmlHttp and a global variable, so it increments for each request. Then if you repeatedly make calls to the same thing (eg it returns online users, or, whatever) then you can actually resubmit using the same element of the array too.

Added example code:

To convert it to a reoccuring event, make a copy of these 2, and in the got data call, just resubmit using reget

  var req_fifo=Array();
  var eleID=Array();
  var i=0;

  function GetAsyncData(myid,url) {
    eleID[i]=myid;
    if (window.XMLHttpRequest) 
    {
      req_fifo[i] = new XMLHttpRequest();
    }
    else if (window.ActiveXObject) 
    {
      req_fifo[i] = new ActiveXObject("Microsoft.XMLHTTP");
    }
      req_fifo[i].abort();
      req_fifo[i].onreadystatechange = function(index){ return function() { GotAsyncData(index); }; }(i);
      req_fifo[i].open("GET", url, true);
      req_fifo[i].send(null);
      i++;
  }
  function GotAsyncData(id) {
    if (req_fifo[id].readyState != 4 || req_fifo[id].status != 200) {
      return;
    }
    document.getElementById(eleID[id]).innerHTML=
      req_fifo[id].responseText;
    req_fifo[id]=null;
    eleID[id]=null;
    return;
  }

  function reget(id) {
    myid=eleID[id];
    url=urlID[id];
      req_fifo[id].abort();
      req_fifo[id].onreadystatechange = function(index){ return function() { GotAsyncData(index); }; }(id);
      req_fifo[id].open("GET", url, true);
      req_fifo[id].send(null);
  }


The suggestions to parameterize your function are correct and would allow you to avoid repeating code.


the jQuery library is also worth considering. http://jquery.com

If you use jQuery, each ajax call would literally be this easy.

$('#mom').load('/index.php?i=mom');

And you could wrap it up as follows if you'd like, since you say you'll be using it many times (and that you want it done when a link is clicked)

function doAjax(imgForAjax) { $('#'+imgForAjax).load('/index.php&i='+imgForAjax);}
doAjax('mom');

It makes the oft-repeated ajax patterns much simpler, and handles the issues between different browsers just as I presume your getXMLhttp function does.

At the website I linked above you can download the library's single 29kb file so you can use it on your pages with a simple <script src='jquery.min.js'></script> There is also a lot of great documentaiton. jQuery is pretty popular and you'll see it has a lot of questions and stuff on SO. ajax is just one of many things that jQuery library/framework (idk the preferred term) can help with.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜