【问题标题】:How to dynamically render a <div> content on click of a button without reloading the whole content?如何在单击按钮时动态呈现 <div> 内容而不重新加载整个内容?
【发布时间】:2018-04-09 08:10:29
【问题描述】:

详情:

<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 信息”按钮时,才会显示 div id “panel-2”中的内容。该按钮应更新 DB 中的记录,然后在不刷新整个页面的情况下呈现 div id "panel-2" 中的内容。如何实现这个要求 - onSubmit() 函数中的任何 ajax 逻辑?

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

【问题讨论】:

    标签: javascript html angularjs ajax


    【解决方案1】:

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

    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";
    }
    <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>

    【讨论】:

    • 感谢您的回复拉西尔。进入 innerHTML 的 html 内容非常庞大,例如 30 行 html 代码。你能想出一种方法来打包那个 html 并在 innerHTML 中调用它吗?
    • 30 行并不大。我已经做了很多次了。你是什​​么意思包装?通常,您的服务器应该返回 HTML 并将重新调整的 Ajax 结果分配给innerHTML,不需要打包,因为服务器会自动压缩它。或者,如果您的服务器返回纯数据,然后您的 JavaScript 获取重新调整的 Ajax 结果并将其格式化为 HTML,那么您将其分配给一个变量并且这里也没有打包。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多