如何在不重新加载整个内容的情况下单击按钮动态呈现<div>内容?

时间:2017-10-27 16:40:24

标签: javascript html angularjs ajax

详细说明:

<div class="row-fluid">
    <div ng-app="sampleAngular">
            <div id="panel-1" ng-controller="Controller1">
              <!-- some html code here that displays a table of information-->
            </div>
            <p><button type="button" onclick="onSubmit();" name="subscribe">Subscribe to Panel-2 Info</button> </p>
            <div id="panel-2" ng-controller="Controller2">
              <!-- some html code here that displays another table of information-->
            </div>
    </div>
</div>

问题: 仅当用户单击“订阅Panel-2 Info”按钮时,才会显示div id“panel-2”中的内容。该按钮应更新DB中的记录,然后在div id“panel-2”中呈现内容而不刷新整个页面。如何实现这个要求 - onSubmit()函数中的任何ajax逻辑?

注意:我不应该渲染整个页面,然后在“panel-2”周围设置 visibility:false ,因为我不应该调用控制器“ ng-controller =“Controller2 ”直到用户订阅(点击按钮)。

1 个答案:

答案 0 :(得分:1)

在你的onSubmit()函数中,进行Ajax调用,该调用应该返回HTML中所需的结果,或者作为数据然后用JavaScript格式化它在JavaScript中并使用innerHTML属性显示它。这是一个示例(单击按钮以查看其工作原理):

&#13;
&#13;
function onSubmit() {
  //make your Ajax call here

  //if the Ajax was successful, display the result
  document.getElementById("panel-2").innerHTML = "some html code here that displays another table of information (this is the result of the Ajax call)";
  //if the Ajax resulted in error, display an error message
  //document.getElementById("panel-2").innerHTML = "an error occurred";
}
&#13;
<div class="row-fluid">
  <div ng-app="sampleAngular">
    <div id="panel-1" ng-controller="Controller1">
      some html code here that displays a table of information
    </div>
    <p><button type="button" onclick="onSubmit();" name="subscribe">Subscribe to Panel-2 Info</button> </p>
    <div id="panel-2" ng-controller="Controller2"></div>
  </div>
</div>
&#13;
&#13;
&#13;