search
HomeWeb Front-endJS TutorialHow does jquery traverse and obtain the list collection from the background?

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" },
function(data){
  //可以在这儿循环,比如:
  var listNow=data.listHouTai;//取list。listHouTai是你后台定义的json名称
  for ( var i = 0; i < listNow.length; i++) { 
       var id = vos[i].Id;//可以取list中第一个对象的id值,其他的类推
  }         
});

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);

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>

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 >

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>


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
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
From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

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

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.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools