search
HomeBackend DevelopmentPHP TutorialAjax realizes the sharing of the strength of dynamically loading data

This article mainly introduces in detail a small example of Ajax dynamic loading of data. It has certain reference value. Interested friends can refer to it. I hope it can help everyone.

Foreword:

1. This essay implements an example of Ajax dynamic loading.

2. Implemented using the .net MVC framework.

3. This example focuses on the front-end and back-end interactions, and the others are abbreviated.

Start:

1. Controller ActionResult code (used to display the page)


    /// <summary>
    /// 电话查询页面
    /// </summary>
    /// <returns></returns>
    public ActionResult PhoneSearch(string sql)
    {
      phoneList=从数据库查询数据;
      ViewBag.phoneList = phoneList;
      return View();
    }

2. Main code of the front page

Description: This is the table to display data, and the fields in it must match the model you have built.


<table border="1" cellspacing="0" cellpadding="0" class="toLang" id="phoneTable">
              <tr>
                <th>序号</th>
                <th>公司</th>
                <th>部门</th>
                <th>小组</th>
                <th>姓名</th>
                <th>职位</th>
                <th>电话</th>
              </tr>
              <tbody id="todeListTBODY">
                @if (ViewBag.phoneList != null)
              {
                foreach (var item in ViewBag.phoneList)
                {
                  number = number + 1;
              <tr>
                <td>@number</td>
                <td>@item.Conpany</td>
                <td>@item.Department</td>
                <td>@item.Team</td>
                 <td>@item.Name</td>
                 <td>@item.Position</td>
                 <td>@item.PhoneNumber</td>
                  </tr>
                }
              }
              </tbody>
            </table>

3. My query conditions


 <p style="display:block;float:left; width:100%; ">
          公司:
          <select class="InputTestStyle" id="company" onclick="initDeptSelect()">
            <option>==请选择公司==</option>
          </select>
          部门:
          <select class="InputTestStyle" id="department" onclick="initGroupSelect()">
            <option>==请选择公司==</option>
          </select>
          小组:
          <select class="InputTestStyle" id="group" onclick="QueryPhoneNum()">
            <option>==请选择公司==</option>
          </select>
 </p>

4. Initialization of query conditions (take the company as an example )

4.1 JavaScript code at the front end


  //打开页面的时候执行
  window.onunload = initCompanySelect();
  //初始化“公司”下拉框
  function initCompanySelect()
  {
    $.ajax({
      type: &#39;POST&#39;,
      url: &#39;/Home/GetCompantListForPhone&#39;,
      dataType: &#39;json&#39;,
      data: { },
      success: function (data) {
        //1.清空这个下拉框的数据
        // $(&#39;#company option&#39;).remove();//也能成功实现
        $(&#39;#company&#39;).empty();
        $("#company").append($(&#39;<option>&#39; + &#39;==请选择公司==&#39; + &#39;</option>&#39;));
        //2.将返回值动态加载进下拉框,动态生成标签。
        for (i = 0; i < data.length;i++)
        {
          $("#company").append($(&#39;<option >&#39; + data[i].Conpany + &#39;</option>&#39;));
        }
      },
      error: function (XMLHttpRequest, textStatus, errorThown) {
        alert("操作失败!");
      }
    })
  }

4.2 ActionResult code corresponding to the initialization drop-down box


/// <summary>
/// 获取电话查询公司下拉数据
/// </summary>
/// <returns></returns>
[HttpPost]
public JsonResult GetCompantListForPhone()
{
  
  compantList = 从数据库获取这个下拉框数据的集合;
  return Json(compantList);
}

After the other two drop-down boxes are completed according to this method. You can query based on conditions. The following two are JavaScript and background methods used in conjunction.

5. Submit the query to the background, and then reassign the table based on the returned set.


//根据条件查询电话
  function QueryPhoneNum()
  {
    if ($(&#39;#group&#39;).val() == &#39;==请选择小组==&#39;)
    {
      return;
    }
    number = 0;
    $.ajax({
      type: &#39;POST&#39;,
      url: &#39;/Home/PhoneSearchSubmit&#39;,
      dataType: &#39;json&#39;,
      data: {
        company:$(&#39;#company&#39;).val(),
        dept: $(&#39;#department&#39;).val(),
        group: $(&#39;#group&#39;).val()
      },
      success: function (phoneList) {
        //1.清空这个表格的数据
        $(&#39;#todeListTBODY tr&#39;).remove();
        
        //2.将返回值动态加载进表格。
        $.each(phoneList, function (index, element) {
          number = number + 1;
          $(&#39;#todeListTBODY&#39;).prepend(function (i) {
            return "<tr>" +
               "<td>" +number +
               "<td>" + element.Conpany +
               "<td>" + element.Department +
               "<td>" + element.Team +
               "<td>" + element.Name +
               "<td>" + element.Position +
               "<td>" + element.PhoneNumber +
               "</tr>";
          })
        })
      },
      error: function (XMLHttpRequest, textStatus, errorThown) {
        alert("操作失败!");
      }
    })
  }

5.1 ActionResult corresponding to the query data


/// <summary>
/// 电话查询
/// </summary>
/// <returns></returns>
[HttpPost]
public JsonResult PhoneSearchSubmit(string company, string dept, string group)
{
  phoneList = 根据条件查询数据;
  return Json(phoneList);
}

Related recommendations:

Ajax realizes the detailed explanation of the dynamic loading of the combo box example

JavaScript uses Ajax to dynamically load the CheckBox check box

How to implement it in Java Dynamically loaded code example

The above is the detailed content of Ajax realizes the sharing of the strength of dynamically loading data. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What is the difference between unset() and session_destroy()?What is the difference between unset() and session_destroy()?May 04, 2025 am 12:19 AM

Thedifferencebetweenunset()andsession_destroy()isthatunset()clearsspecificsessionvariableswhilekeepingthesessionactive,whereassession_destroy()terminatestheentiresession.1)Useunset()toremovespecificsessionvariableswithoutaffectingthesession'soveralls

What is sticky sessions (session affinity) in the context of load balancing?What is sticky sessions (session affinity) in the context of load balancing?May 04, 2025 am 12:16 AM

Stickysessionsensureuserrequestsareroutedtothesameserverforsessiondataconsistency.1)SessionIdentificationassignsuserstoserversusingcookiesorURLmodifications.2)ConsistentRoutingdirectssubsequentrequeststothesameserver.3)LoadBalancingdistributesnewuser

What are the different session save handlers available in PHP?What are the different session save handlers available in PHP?May 04, 2025 am 12:14 AM

PHPoffersvarioussessionsavehandlers:1)Files:Default,simplebutmaybottleneckonhigh-trafficsites.2)Memcached:High-performance,idealforspeed-criticalapplications.3)Redis:SimilartoMemcached,withaddedpersistence.4)Databases:Offerscontrol,usefulforintegrati

What is a session in PHP, and why are they used?What is a session in PHP, and why are they used?May 04, 2025 am 12:12 AM

Session in PHP is a mechanism for saving user data on the server side to maintain state between multiple requests. Specifically, 1) the session is started by the session_start() function, and data is stored and read through the $_SESSION super global array; 2) the session data is stored in the server's temporary files by default, but can be optimized through database or memory storage; 3) the session can be used to realize user login status tracking and shopping cart management functions; 4) Pay attention to the secure transmission and performance optimization of the session to ensure the security and efficiency of the application.

Explain the lifecycle of a PHP session.Explain the lifecycle of a PHP session.May 04, 2025 am 12:04 AM

PHPsessionsstartwithsession_start(),whichgeneratesauniqueIDandcreatesaserverfile;theypersistacrossrequestsandcanbemanuallyendedwithsession_destroy().1)Sessionsbeginwhensession_start()iscalled,creatingauniqueIDandserverfile.2)Theycontinueasdataisloade

What is the difference between absolute and idle session timeouts?What is the difference between absolute and idle session timeouts?May 03, 2025 am 12:21 AM

Absolute session timeout starts at the time of session creation, while an idle session timeout starts at the time of user's no operation. Absolute session timeout is suitable for scenarios where strict control of the session life cycle is required, such as financial applications; idle session timeout is suitable for applications that want users to keep their session active for a long time, such as social media.

What steps would you take if sessions aren't working on your server?What steps would you take if sessions aren't working on your server?May 03, 2025 am 12:19 AM

The server session failure can be solved through the following steps: 1. Check the server configuration to ensure that the session is set correctly. 2. Verify client cookies, confirm that the browser supports it and send it correctly. 3. Check session storage services, such as Redis, to ensure that they are running normally. 4. Review the application code to ensure the correct session logic. Through these steps, conversation problems can be effectively diagnosed and repaired and user experience can be improved.

What is the significance of the session_start() function?What is the significance of the session_start() function?May 03, 2025 am 12:18 AM

session_start()iscrucialinPHPformanagingusersessions.1)Itinitiatesanewsessionifnoneexists,2)resumesanexistingsession,and3)setsasessioncookieforcontinuityacrossrequests,enablingapplicationslikeuserauthenticationandpersonalizedcontent.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor