如何在AJAX函数中按属性组织对象

时间:2015-06-28 22:33:25

标签: javascript jquery html ajax

请原谅我,如果这看起来很简单,我已经坚持了几个星期。 如果您使用AJAX成功函数在html页面上动态显示数据,那么从服务器返回的数据就是stdclass对象,如此

    array( 
       [7] => stdClass Object
        (
       [id] => 3
       [title] => Electrition
       [img] => 
       [description] => 
       [school] => 
       [location] => 1
       [url] => 
       [tablename] => 3
       [votes] => 0
       [name] => John Doe
       [NumJobsdone] => 4
           )

         [8] => stdClass Object
       (
        [id] => 2
        [title] => Electrition
        [img] => 
        [description] => 
        [school] => 
        [location] => 1
        [url] => 
        [tablename] => 2
        [votes] => 0
        [name] => Tico Marinez
        [NumJobsdone] => 6
        )

        [9] => stdClass Object
        (
        [id] => 2
        [title] => Engineer
        [img] => 
        [description] => 
        [school] => 
        [location] => 1
        [tablename] => 2
        [votes] => 0
        [name] => Jerry Smity
        [NumJobsdone] => 6
       )

     [10] => stdClass Object
       (
       [id] => 2
       [title] => Engineer
       [img] => 
       [description] => 
       [school] => 
       [location] => 1
       [url] => 
       [tablename] => 2
       [votes] => 0
        [name] => Laura Bastian
       [NumJobsdone] => 6
         )
        ) 

如何编写一个jquery函数,它可以迭代数据并创建段落标记来标记输出和相应对象div中的无序列表?

离。你正在尝试创建两个分组,电子和工程师,并列出个人的名字。

看起来很简单,但是当我在成功函数中使用$ .each方法时,我为每个具有我正在组织对象的属性的对象创建了一个段落标记,当我尝试使用排序方法时,我只能一次比较两个或三个对象,而不是遍历多个对象的长列表。

假设所需的输出看起来像这样

     <div id="accordion">
        <p> Electrition</p>
        <div>
        <ul>
          <li>jon</li>
          <li>jill</li>         
       </ul>
       </div>

        <p>Engineer</p>
       <div>
        <ul>
          <li>jerry</li>
          <li>laura</li>
       </ul>
      </div>
      </div>

1 个答案:

答案 0 :(得分:0)

尝试每个jquery ..

$.each(array, function (index,value) {
$('#accordion').append("<p>"+ value.title +"</p><div><ul><li>" + value.name + "</li></ul></div>")});

array是要传回的数组的名称 I created a codepen solution for you你可以用其他元素做更多的事情

  

Jquery each question

     

JQuery Each