Home Web Front-end JS Tutorial How does jquery traverse and obtain the list collection from the background?

How does jquery traverse and obtain the list collection from the background?

Jun 17, 2017 am 09:53 AM
jquery Backstage how Traverse

In the project, jquery obtains the list from the background. How does it traverse it?

Under normal circumstances, the list in the background should be converted into a json string and returned to the callback function of ajax. The json string can be directly manipulated in the callback function.

For example:

$.post("test.php", { name: "John", time: "2pm" },
Copy after login
function(data){
  //可以在这儿循环,比如:
  var listNow=data.listHouTai;//取list。listHouTai是你后台定义的json名称
  for ( var i = 0; i < listNow.length; i++) { 
       var id = vos[i].Id;//可以取list中第一个对象的id值,其他的类推
  }         
});
Copy after login

You can use a jQuery custom array operation classjs external file, the prerequisite is to introduce the jQuery class library. The encapsulation class code is as follows:

(function ($) {
    $.List = function () {
        var _list = new Array();
        //外部为数组赋值
        this.GetDataSource = function (arr) {
            if (IsArrayType(arr)) {
                _list = arr;
            } else {
                alert("指定元素非数组类型,赋值失败!");
            }
        };
        //添加一个元素
        this.Add = function (arg) {
            if (arg) {
                _list.push(arg);
            } else {
                alert("参数错误,添加元素失败!");
            }
            return _list;
        };
        //删除指定索引的元素
        this.RemoveAt = function (index) {
            if (IsArrayIndex(index) && index < _list.length) {
                var i;
                var arr = new Array();
                for (i = 0; i < _list.length; i++) {
                    if (i != index) {
                        arr.push(_list[i]);
                    }
                }
                _list = arr;
                return _list;
            }
            else {
                alert("未获取到设置对象的实例,删除元素失败!");
            }
        };
        //按照指定的分割符显示出所有元素
        this.Split = function (arg) {
            arg = arg || ",";
            var i, res;
            res = "";
            if (_list.length > 0) {
                for (i = 0; i < _list.length; i++) {
                    res += _list[i].toString() + arg;
                }
                return res.substr(0, (res.length - arg.toString().length));
            } else {
                return "";
            }
        };
        //外部调用直接返回当前数组实力
        this.ToArray = function () {
            return _list;
        };
        //设置指定索引处的值为指定值
        this.Update = function (index, value) {
            if (IsArrayIndex(index) && index < _list.length) {
                _list[index] = value;
            }
            return _list;
        };
        //清空所有元素
        this.RemoveAll = function () {
            _list.splice(0, _list.length);
            return _list;
        };
        //根据传入的值获取第一次出现在数组中的下标
        this.IndexOf = function (value) {
            if (value) {
                var i;
                for (i = 0; i < _list.length; i++) {
                    if (_list[i] == value) {
                        return i;
                    }
                }
            }
            return -1;
        };
        //获取数组长度
        this.Size = function () {
            return _list.length;
        };
        //移除数组中重复的项
        this.RemoveRepeat = function () {
            _list.sort();
            var rs = [];
            var cr = false;
            for (var i = 0; i < _list.length; i++) {
                if (!cr)
                    cr = _list[i];
                else if (cr == _list[i])
                    rs[rs.length] = i;
                else
                    cr = _list[i];
            }
            for (var i = rs.length - 1; i >= 0; i--)
                this.RemoveAt(rs[i]);
            return _list;
        };
        //对数字数组元素排序,参数:0升序1降序
        this.SortNumber = function (f) {
            if (!f) f = 0;
            if (f == 1) return _list.sort(function (a, b) { return b - a; });
            return _list.sort(function (a, b) { return a - b; });
        };

        //私有方法
        //判断正确的数组下标
        function IsArrayIndex(index) {
            var reg = /^\d+$/;
            if (reg.test(index))
                return true;
            else
                return false;
        }
        //判断当前对象是否为数组对象
        function IsArrayType(arr) {
            if (typeof arr == &#39;object&#39; && typeof arr.length == &#39;number&#39;)
                return true;
            else
                return false;
        }
    }; //结束List的构造方法

})(jquery);
Copy after login

Two js files need to be introduced when calling the page:

<script src="js/jquery-1.8.3.min.js" type="text/JavaScript"></script>
<script src="js/jquery.array.js" type="text/javascript"></script>
<script type="text/javascript">
 $(function () {
            var myList = new $.List();
            myList.Add(1);
            myList.Add("1906-07-08");
            myList.Add("hellow world");
            myList.RemoveAt(0);
            myList.Update(0, "11111111");
            //alert("数组被修改内容后的结果:" + myList.Split("|"));
            myList.RemoveAll();
            var arr = myList.ToArray();
            //alert("数组全部被删除后结果:" + arr);
            //alert("数组1当前长度:" + myList.Size());
            var myList2 = new $.List();
            myList2.Add(3);
            myList2.Add(1);
            myList2.Add(45);
            myList2.Add(21);
            myList2.Add(-9);
            myList2.Add(1);
            alert("第二个实例数组结果:" + myList2.ToArray());
            myList2.RemoveRepeat();
            alert("去重后第二个实例数组结果:" + myList2.ToArray());
            alert("去重后第二个实例数组长度:" + myList2.Size());
            myList2.SortNumber(1);
            alert("排序后的数组:" + myList2.ToArray());
            var arr3 = ["aaa", "bbb", "ccc", "ddd", "eee"];
            var arr4;
            myList2.GetDataSource(arr3);
            alert("重新赋值后结果:"+myList2.ToArray());
        });
    </script>
Copy after login

Object syntax JSON data format (when the server calls back The object data format is json data format, and the format requirements of JSON must be met. The callback object must be converted using the eval function (otherwise, the Object will not be obtained). This article will not introduce the data issues of the server-side callback in detail. We will directly customize the object. )

1.jqueryTraverse the object

< !DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" > <HTML > <HEAD > <TITLE > New Document < /TITLE>
  <script language="javascript" type="text/javascript " src="jquery.min.js "></script>
  <script  type="text / javascript ">
     $(function(){
       var tbody = "";    
    //------------遍历对象 .each的使用-------------
    
    var obj =[{"name ":"项海军","password ":"123456 "}];
   $("#result ").html("------------遍历对象.each的使用-------------");
      alert(obj);//是个object元素
   //下面使用each进行遍历
   $.each(obj,function(n,value) { 
           alert(n+&#39; &#39;+value);
           var trs = "";
             trs += " < tr > <td > " + value.name +" < /td> <td>" + value.password +"</td > </tr>";
             tbody += trs;       
           });
         $("#project").append(tbody);
     
  });
  </script > </HEAD>
 
 <BODY>
     <div id="result" style="font-size:16px;color:red;"></div > <table cellpadding = 5 cellspacing = 1 width = 620 id = "project"border = "1" > <tr > <th > 用户名 < /th>
                <th>密码</th > </tr>             
     </table > </BODY>
</HTML >
Copy after login

2.jQueryTraverse the array

< !DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" > <HTML > <HEAD > <TITLE > New Document < /TITLE>
  <script language="javascript" type="text/javascript " src="jquery.min.js "></script>
  <script  type="text / javascript ">
     $(function(){
       var tbody = "";
    
     //------------遍历数组 .each的使用-------------
           var anArray = [&#39;one&#39;,&#39;two&#39;,&#39;three&#39;];
     $("#result ").html("------------遍历数组.each的使用-------------");
           $.each(anArray,function(n,value) {
           
            alert(n+&#39; &#39;+value);
           var trs = "";
             trs += " < tr > <td > " +value+" < /td></tr > ";
              tbody += trs;
            });
          $("#project ").append(tbody);
     
  });
  </script>
 </HEAD>
 
 <BODY>
    ------------此部分同1中的body部分--------------------
 </BODY>
</HTML>
3.jQuery 遍历List集合(其实与遍历一个对象没有太大区别,只是格式上的问题)
<!DOCTYPE HTML PUBLIC " - //W3C//DTD HTML 4.0 Transitional//EN">
< HTML > <HEAD > <TITLE > New Document < /TITLE>
  <script language="javascript" type="text/javascript " src="jquery.min.js "></script>
  <script  type="text / javascript ">
     $(function(){
       var tbody = "";
    
     //------------遍历List集合 .each的使用-------------
      var obj =[{"name ":"项海军","password ":"123456 "},{"name ":"科比","password ":"333333 "}];
    $("#result ").html("遍历List集合.each的使用");
      alert(obj);//是个object元素
   //下面使用each进行遍历
   $.each(obj,function(n,value) { 
           alert(n+&#39; &#39;+value);
       var trs = "";
             trs += " < tr > <td > " +value.name+" < /td> <td>" + value.password +"</td > </tr>";
             tbody += trs;       
           });
         $("#project").append(tbody);
     
  });
  </script > </HEAD>
 
 <BODY>
       ------------此部分同1中的body部分--------------------
 </BODY >
</HTML>
Copy after login


The above is the detailed content of How does jquery traverse and obtain the list collection from the background?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Discuz background login problem solution revealed Discuz background login problem solution revealed Mar 03, 2024 am 08:57 AM

The solution to the Discuz background login problem is revealed. Specific code examples are needed. With the rapid development of the Internet, website construction has become more and more common, and Discuz, as a commonly used forum website building system, has been favored by many webmasters. However, precisely because of its powerful functions, sometimes we encounter some problems when using Discuz, such as background login problems. Today, we will reveal the solution to the Discuz background login problem and provide specific code examples. We hope to help those in need.

Are you worried about WordPress backend garbled code? Try these solutions Are you worried about WordPress backend garbled code? Try these solutions Mar 05, 2024 pm 09:27 PM

Are you worried about WordPress backend garbled code? Try these solutions, specific code examples are required. With the widespread application of WordPress in website construction, many users may encounter the problem of garbled code in the WordPress backend. This kind of problem will cause the background management interface to display garbled characters, causing great trouble to users. This article will introduce some common solutions to help users solve the trouble of garbled characters in the WordPress backend. Modify the wp-config.php file and open wp-config.

Java how to loop through a folder and get all file names Java how to loop through a folder and get all file names Mar 29, 2024 pm 01:24 PM

Java is a popular programming language with powerful file handling capabilities. In Java, traversing a folder and getting all file names is a common operation, which can help us quickly locate and process files in a specific directory. This article will introduce how to implement a method of traversing a folder and getting all file names in Java, and provide specific code examples. 1. Use the recursive method to traverse the folder. We can use the recursive method to traverse the folder. The recursive method is a way of calling itself, which can effectively traverse the folder.

How to use PUT request method in jQuery? How to use PUT request method in jQuery? Feb 28, 2024 pm 03:12 PM

How to use PUT request method in jQuery? In jQuery, the method of sending a PUT request is similar to sending other types of requests, but you need to pay attention to some details and parameter settings. PUT requests are typically used to update resources, such as updating data in a database or updating files on the server. The following is a specific code example using the PUT request method in jQuery. First, make sure you include the jQuery library file, then you can send a PUT request via: $.ajax({u

How to identify genuine and fake shoe boxes of Nike shoes (master one trick to easily identify them) How to identify genuine and fake shoe boxes of Nike shoes (master one trick to easily identify them) Sep 02, 2024 pm 04:11 PM

As a world-renowned sports brand, Nike's shoes have attracted much attention. However, there are also a large number of counterfeit products on the market, including fake Nike shoe boxes. Distinguishing genuine shoe boxes from fake ones is crucial to protecting the rights and interests of consumers. This article will provide you with some simple and effective methods to help you distinguish between real and fake shoe boxes. 1: Outer packaging title By observing the outer packaging of Nike shoe boxes, you can find many subtle differences. Genuine Nike shoe boxes usually have high-quality paper materials that are smooth to the touch and have no obvious pungent smell. The fonts and logos on authentic shoe boxes are usually clear and detailed, and there are no blurs or color inconsistencies. 2: LOGO hot stamping title. The LOGO on Nike shoe boxes is usually hot stamping. The hot stamping part on the genuine shoe box will show

jQuery Tips: Quickly modify the text of all a tags on the page jQuery Tips: Quickly modify the text of all a tags on the page Feb 28, 2024 pm 09:06 PM

Title: jQuery Tips: Quickly modify the text of all a tags on the page In web development, we often need to modify and operate elements on the page. When using jQuery, sometimes you need to modify the text content of all a tags in the page at once, which can save time and energy. The following will introduce how to use jQuery to quickly modify the text of all a tags on the page, and give specific code examples. First, we need to introduce the jQuery library file and ensure that the following code is introduced into the page: &lt

Discuz background account login exception, how to deal with it? Discuz background account login exception, how to deal with it? Mar 09, 2024 pm 05:51 PM

Title: Discuz background account login exception, how to deal with it? When you use the backend management of the Discuz forum system, you may sometimes encounter abnormal account login. This could be due to a variety of reasons, including a wrong password, account being blocked, network connection issues, etc. When encountering this situation, we need to solve the problem through simple troubleshooting and processing. Check whether the account number and password are correct: First, confirm whether the account number and password you entered are correct. When logging in, make sure the capitalization is correct and the password is

Use jQuery to modify the text content of all a tags Use jQuery to modify the text content of all a tags Feb 28, 2024 pm 05:42 PM

Title: Use jQuery to modify the text content of all a tags. jQuery is a popular JavaScript library that is widely used to handle DOM operations. In web development, we often encounter the need to modify the text content of the link tag (a tag) on ​​the page. This article will explain how to use jQuery to achieve this goal, and provide specific code examples. First, we need to introduce the jQuery library into the page. Add the following code in the HTML file:

See all articles