2016-04-06 16 views
0

在我看来,我必须按照用户的状态恢复用户。 (这是一个树枝视图,我在一个symfony项目上工作,但这里的后端进程已经构建)清空div的先前内容以便用另一个替换为使用ajax

该视图包含3个按钮(完全标记)和一个表。事实上,它就像创建一个过滤器,以便在表格中显示其状态后的用户。

3状态是可能的:

  • 等待验证=>pending_validation
  • 启用
  • 禁用

这是我在我的html视图代码:

{# the div containing the menu #} 
<div> 
    <ul class="nav navbar-nav navbar-right nav nav-pills link-right"> 
    <li class="active getState" id="enabled"> 
     <a href="#enabled"> 
     <b>User enabled</b> 
     </a> 
    </li> 
    <li class="getState" id="disabled"> 
     <a href="#disabled"> 
     <b>User disabled</b> 
     </a> 
    </li> 
    <li class="getState" id="pending_validation"> 
     <a href="#pending_validation"> 
     <b>User attempting validation</b> 
     </a> 
    </li> 
    </ul> 
</div> 

{# the div containing the table of user #} 
<div id="userInfo"> 
    {% if (users|length == 0) %} 
    <p> <i>No users are availabled for the choosen statement you click on !</i></p> 
    {% else %} 
    <table class="table table-condensed"> 
    <thead> 
     <tr> 
     <th> 
      USERS 
     </th> 
     </tr> 
    </thead> 
    <tbody> 
     <tr> 
     <td> 
      <div> 
      <table class="table table-striped"> 
       <tbody> 
       {% for user in users %} 
       <tr> 
        <td> 
        <b>{{ user.id }}</b> 
        </td> 
        <td> 
        <b>{{ user.username }}</b> 
        </td> 
        <td> 
        <b>{{ user.email }}</b> 
        </td> 
        <td> 
        {{ user.created_at|date}} 
        </td> 
        <td> 
        </td> 
        <td> 
        <a href="{{path('edit', { 'slug': user.slug })}}"> 
         <button> 
         EDIT 
         </button> 
        </a> 
        </td> 
       </tr> 
       {% endfor %} 
       </tbody> 
      </table> 
      </div> 
     </td> 
     </tr> 
    </tbody> 
    </table> 
</div> 

所以,正如你所理解的,当管理员点击按钮时,我必须使用jQuery在JavaScript中以正确的状态显示正确的用户表。

<script type="text/javascript" charset="utf-8" defer> 
    $('.getState').bind('click', function(){ 
    var userInfoDiv = $('#userInfo'); 
    $('.active').removeClass("active"); 
    $(this).addClass("active"); 
    $.ajax({ 
     type: "GET", 
     cache: false, 
     url: "{{ path('index_user_admin') }}", 
     data: { 
      state: $(this).attr("id") 
     }, 
     success: function(html){ 
      userInfoDiv.html(''); 
      var newuserInfoDiv = $(html).find('#userInfo'); 
      userInfoDiv.replaceWith(newuserInfoDiv); 
      userInfoDiv = newuserInfoDiv; 
     } 
    }); 
    }); 
</script> 

正如你能理解,我的Ajax请求的URL参数为url: "{{ path('index_user_admin') }}"和retuns含股利菜单和桌上的整个HTML视图:

我使用jQuery写在JavaScript的代码。

ajax请求效果很好,我恢复了我的用户信息。除了一件事发生,我真的不知道如何解决这个问题。

一旦我点击一个按钮,它会加载并显示我的用户数据,但它会添加它,而不是恢复实际的我想替换为我点击的新的代码。

我想在这里做的是用我点击一个按钮时调用的新内容替换实际内容。 现在,我的以前的数据必须被删除,才能被新的用户信息取代,事实并非如此,事实上没有数据被删除,只有新的数据被添加到前一个。

回答

0

我找到了一个解决方案,好像我在这里做了一个菜鸟的错误,我的ajax调用。

事实上,在我的ajax请求中,而不是这个userInfoDiv.replaceWith(newuserInfoDiv);,我用userInfoDiv.append(newuserInfoDiv);取代了这一点,并且所有工作都很好。