简体   繁体   English

如何在不重复代码的情况下调用多个AJAX函数(至PHP)

[英]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. 我有一个使用AJAX和PHP来显示图像的小脚本。 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. 您可以在下面看到,如果我调用函数mom(),它将在PHP文件index.php?i = mom中查找并显示我要查找的图像。

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. 但是我需要使javascript更轻巧,因为我有30张图像,并且每张图像我都必须修改和复制以下脚本。 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.open("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 : 并修改您的HTML,以便使用正确的参数调用该函数:

<!-- 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>

I solved this by making an array of in your case xmlHttp and a global variable, so it increments for each request. 我通过在您的情况下创建一个xmlHttp数组和一个全局变量来解决此问题,因此对于每个请求它都会递增。 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 要将其转换为重复发生的事件,请复制这两个事件,然后在get数据调用中,只需使用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);
  }

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. MARTIN的解决方案将完美运行。

By the way you should use some javascript framework for Ajax handling like jQuery. 顺便说一下,您应该使用一些javascript框架来进行Ajax处理,例如jQuery。

It will make your life easy. 这将使您的生活变得轻松。

If you are having light weight images you preload the images on your page. 如果图像较轻,则将图像预加载到页面上。

The suggestions to parameterize your function are correct and would allow you to avoid repeating code. 参数化函数的建议是正确的,并且可以避免重复代码。


the jQuery library is also worth considering. jQuery库也值得考虑。 http://jquery.com http://jquery.com

If you use jQuery, each ajax call would literally be this easy. 如果使用jQuery,则每个ajax调用实际上都将如此简单。

$('#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. 它使经常重复的ajax模式变得更加简单,并像假定您的getXMLhttp函数一样处理不同浏览器之间的问题。

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. 在上面我链接的网站上,您可以下载该库的单个29kb文件,因此您可以通过简单的<script src='jquery.min.js'></script>在您的页面上使用它,此外,还有很多很棒的文档资料。 jQuery is pretty popular and you'll see it has a lot of questions and stuff on SO. jQuery非常流行,您会看到它在SO上存在很多问题。 ajax is just one of many things that jQuery library/framework (idk the preferred term) can help with. ajax只是jQuery库/框架(idk是首选术语)可以帮助的众多功能之一。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM