65.9K
CodeProject 正在变化。 阅读更多。
Home

简单动态 JavaScript Ajax 函数

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.09/5 (5投票s)

2018 年 12 月 19 日

CPOL

3分钟阅读

viewsIcon

12743

downloadIcon

170

简单紧凑的可重用原生 JavaScript 函数,您可以轻松地在您的网页中使用它来运行 Ajax 并避免刷新

引言

通常,Ajax 和 JavaScript 对于初学者来说很难开发或理解。而且,它需要编写更多的代码。

仅使用一个函数 AjaxCall() 就能在网页上运行 Ajax,从而实现动态功能。它允许初学者在任何网页上运行 Ajax 代码,而无需额外的代码或外部库。它有助于尽可能简化和运行 Ajax 请求,并具有最大的灵活性。

背景

在我的最后一个项目中,我想设计和开发“单页设计”,它应该是完全功能性的,与后端连接,没有任何客户端刷新。经过多次试验和优化后,我找到了这个 JavaScript 函数来优化 Ajax 调用,它可以用于任何 Web 项目。所以我决定与世界分享它。

Using the Code

为了描述函数 AjaxCall(),我将把它分成三个部分

  1. 参数
  2. body
  3. 呼叫

以下是详细信息

1. 参数

在深入研究之前,您可以简单地使用以下示例调用该函数

AjaxCall("ServerPage.php")

只有一个强制参数,即 serverFile Parameter1: serverFile:这是 Ajax 运行时将调用的文件。它将包含:文件名和参数,例如:“FileName.php?id=111&y=222” 等等。

对于其他参数

参数 2: ControlId: control Id 是您需要结果显示在哪个控件上的 ID: “innerHTML attribute

参数 3: attName

  • empty ('' ):Ajax 将运行,但结果文本将不会显示。
  • not Empty:如果您需要将结果填充到属性中,例如 “BG-Color”,class 等。

参数 3: callId:此调用的标识变量,因此您可以知道哪个反馈对应哪个请求。此 call id 也将包含在函数中。

参数 4: Device: (可选) 如果您重复使用一个参数,例如:分类,为了更容易让您控制页面中的输出位置,您可以将其写入 device 中...

参数 5: Async: 这是 Ajax 的调用类型。默认情况下,它将是 Async,这意味着页面不会等待服务器的响应,这意味着您的代码永远不会因为 Ajax 而挂起。但在某些情况下,您需要将其设置为 false,因为所有应用程序可能都基于此调用,所以在这些情况下它应该是 false。顺便说一句,我不建议将其设置为 false

参数 6: Timeout: 这是等待 Ajax 从服务器返回结果的时间
默认值:5 秒

2. 函数体

这是函数 AjaxCall() 的完整函数体。

如果您有兴趣了解函数体的详细信息,您可以查看注释。

	function AjaxCall(serverFile=null,controlId=null,attName='', 
    callId='',device='robot',async=true,timeout='5000') {
    document.getElementById("divglobalstatuscontent").innerHTML="loading..";
    
  if (serverFile==''|| serverFile==null) {
      //"AjaxCall : ServerFile Empty"
      return;
  }        
  if (window.XMLHttpRequest) {
    // code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
  } else {  // code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
        xmlhttp.ontimeout = function () {
        //addLog("The request TimeOut  "+serverFile);
             document.getElementById("divglobalstatuscontent").innerHTML="time out";
    };
  xmlhttp.onreadystatechange=function() {
    if (this.readyState==4 && this.status==200) {
        var address= this.responseText;
        if(attName=='')
            {
        if(controlId !=''&& controlId)
            {  
                document.getElementById(controlId).innerHTML = this.responseText; 
            }
            }
        else
            {
                 document.getElementById(controlId).setAttribute(attName,this.responseText); 
            }
         //addLog("AjaxCall: "+callId+"STATUS="+this.status+",VALUE="+this.responseText);
        
        switch(device) //if you filled the device , 
          // you can categorize the result into Divs in your page .. Here is some examples: 
            {
                    case("robot"):
                    document.getElementById("divrobotstatusbar").innerHTML = this.responseText;
                    break;
                    case("cam"): 
                    document.getElementById("divcamstatusbar").innerHTML = this.responseText;
                    break;
                    case("led"):
                    document.getElementById("divledstatusbar").innerHTML = this.responseText;
                    break;
                    case('notification'):
                    break;
                    case("move"):
                        document.getElementById("divmovestatusbar").innerHTML = this.responseText;
                    break;
                    case('global'):
                    break;
                default:
                    document.getElementById("divglobalstatuscontent").innerHTML=this.responseText; 
            }
         document.getElementById("divglobalstatuscontent").innerHTML="Success call";         
     return true;
    }
      else{
          
          //request failed.
          //document.getElementById("divglobalstatuscontent").innerHTML="...";
      }
  }
  xmlhttp.open("GET",serverFile,async);
  xmlhttp.timeout=timeout;
  xmlhttp.send();
}

3. 调用

要调用该函数,您可以简单地使用代码和页面中的任何按钮或任何控件,例如

示例 1:调用 Ajax 并将结果输出到 div

AjaxCall("backend.php?device=robot¶m=getConnectionStatus","divconnectionicon");

在此示例中,AjaxCall 将调用文件:BackEnd.php 并带有一些参数。

然后,将结果返回到页面中的 divResult inner HTML 属性。

在 HTML 中,您应该有类似这样的内容

	< div id="divResult">  RESULT OF AJAX CALL < / div>

示例 2 (Class 属性)

AjaxCall("backend.php?device=robot¶m=getConnectionStatus","divconnectionicon","Class",'global'); 

在此示例中,AjaxCall 将调用文件:BackEnd.php 并带有一些参数。

然后,将结果返回到页面中的 divconnectionicon,在 Class 属性中。

结果将是这样的

< div id="" class="RESULT of Ajax call ">< / div>

历史

有关更多示例和更新,您可以查看我们的 GitHub 代码

© . All rights reserved.