>  기사  >  웹 프론트엔드  >  JQuery+Ajax를 사용하여 테이블을 동적으로 생성하는 단계에 대한 자세한 설명

JQuery+Ajax를 사용하여 테이블을 동적으로 생성하는 단계에 대한 자세한 설명

php中世界最好的语言
php中世界最好的语言원래의
2018-04-24 11:57:001964검색

이번에는 JQuery+Ajax를 사용하여 테이블을 동적으로 생성하는 단계에 대해 자세히 설명하고, JQuery+Ajax를 사용하여 테이블을 동적으로 생성할 때 주의 사항은 무엇인지 살펴보겠습니다.

머리말:

이 예제의 대략적인 기능은 프런트엔드가 JQuery의 Ajax를 통해 일반 핸들러(Handler)를 호출하고

테이블에 표시해야 하는 정보를 얻은 다음 이를 json 형식으로 변환하는 것입니다. 프런트엔드가 데이터를 얻은 후 루프를 실행하여 이를 프런트엔드로 반환합니다. 테이블의 행을 작성하려면 테이블에 행을 추가하는 것이 가장 좋습니다.

목표:

 a 간단한 JQuery Ajax 사용에 익숙해지기

 b 기본 Json 형식 데이터 구성 방법 이해(Json은 타사 dll을 통해서도 구성 가능)

 c 기본 핸들러 사용법

1 간단한 렌더링

2 프런트엔드 코드

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="DialogAjax.aspx.cs" Inherits="JQueryTest_DialogAjax" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
  <title></title>
  <link href="../JQueryUi/jquery-ui-1.8.5.custom.css" rel="stylesheet" type="text/css" />
  <script src="../JQueryUi/jquery-1.4.2.min.js" type="text/javascript"></script>
  <script src="../JQueryUi/jquery-ui-1.8.5.custom.min.js" type="text/javascript"></script>
  <style type="text/css">
    #pTb
    {
      width:800px;
      border:1px solid #aaa;
      margin:0 auto;
    }
    .even{background:#CCCCCC;}
    .odd{background:#FFFFFF;}
  </style>
  <script type="text/javascript">
    //获取发布模块类型
    function getModuleInfo() {
      $.ajax({
        type: "GET",
        dataType: "json",
        url: "../Handler/TestHandler.ashx?Method=GetModuleInfo",
        //data: { id: id, name: name },
        success: function(json) {
          var typeData = json.Module;
          $.each(typeData, function(i, n) {
            var tbBody = ""
            var trColor;
            if (i % 2 == 0) {
              trColor = "even";
            }
            else {
              trColor = "odd";
            }
            tbBody += "<tr class=&#39;" + trColor + "&#39;><td>" + n.ModuleNum + "</td>" + "<td>" + n.ModuleName + "</td>" + "<td>" + n.ModuleDes + "</td></tr>";
            $("#myTb").append(tbBody);
          });
        },
        error: function(json) {
          alert("加载失败");
        }
      });
    }
    $(function() {
      getModuleInfo();
    });
  </script>
</head>
<body>
  <form id="form1" runat="server">
  <p id="pTb">
    <table id="myTb" style=" width:100%">
    </table>
  </p>
  </form>
</body>
</html>

3 핸들러 코드

<%@ WebHandler Language="C#" Class="TestHandler" %>
using System;
using System.Web;
using System.Collections.Generic;
using System.Text;
using DataDAL;
using DataEnity;
public class TestHandler : IHttpHandler {
  HttpRequest Request;
  HttpResponse Response;
  public void ProcessRequest (HttpContext context) {
    //不让浏览器缓存
    context.Response.Buffer = true;
    context.Response.ExpiresAbsolute = DateTime.Now.AddDays(-1);
    context.Response.AddHeader("pragma", "no-cache");
    context.Response.AddHeader("cache-control", "");
    context.Response.CacheControl = "no-cache";
    context.Response.ContentType = "text/plain";
    Request = context.Request;
    Response = context.Response;
    string method = Request["Method"].ToString();
    System.Reflection.MethodInfo methodInfo = this.GetType().GetMethod(method);
    methodInfo.Invoke(this, null);
  }
  public void GetModuleInfo()
  {
    StringBuilder sb = new StringBuilder();
    string jsonData = string.Empty;
    List<Module> lsModule = ModuleDAL.GetModuleList();
    sb.Append("{\"Module\":[");
    for (int i = 0; i < lsModule.Count; i++)
    {
      jsonData = "{\"ModuleNum\":" + "\"" + lsModule[i].ModuleNum + "\"" + ",\"ModuleName\":" + "\"" + lsModule[i].ModuleName + "\"" + ",\"ModuleDes\":" + "\"" + lsModule[i].ModuleDes + "\"" + "},";
      sb.Append(jsonData);
    }
    if (lsModule.Count > 0)
      sb = sb.Remove(sb.Length - 1, 1);
    sb.Append("]}");
    Response.Write(sb);
  }
  public bool IsReusable
  {
    get {
      return false;
    }
  }
}
이 글의 사례를 읽으신 후 방법을 마스터하셨으리라 믿습니다. 흥미로운 정보가 있으니 PHP 중국어 웹사이트의 다른 관련 기사도 주목해 주세요!

추천 도서:

jQuery 필터 메소드 filter()

jQuery LigerUI 연산 양식
사용에 대한 자세한 설명

위 내용은 JQuery+Ajax를 사용하여 테이블을 동적으로 생성하는 단계에 대한 자세한 설명의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.