完全加载AJAX获取的HTML后加载Javascript

时间:2015-05-08 20:17:03

标签: javascript php html ajax

我的情况是HTML部分用AJAX加载到DIV中,ID ="动态内容"使用 main.js 脚本。这个脚本位于 main.php 的HEAD部分内,它是这样的:

$.ajax({
            url: 'content.php',
            success: function(output){

                $('#dynamic-content').html(output);
            }       
    });

负责控制该内容的Javascript文件位于另一个名为 secondary.js 的JS文件中。此文件在 main.php 内再次关闭BODY之前。

main.php文档结构:

<html>
  <head>
    <script type="text/javascript" src="js/main.js"></script>
  </head>

  <body>
    ....
    <div id="dynamic-content"></div>
    ....
    ....
    <script type="text/javascript" src="js/secondary.js"></script> 
   </body>
</html>

有时 content.php 的内容太大,而 secondary.js 文件在内容完全加载之前加载。因此,一些元素不是针对性的,我有问题。

有没有办法让我延迟1-2秒执行secondary.js,只是为了确保内容已满载?

ps:以上所有文件都托管在同一台服务器上

提前致谢。

4 个答案:

答案 0 :(得分:1)

您尝试实现的是异步行为。无论secondary.js做什么,都将它放在一个函数中并在ajax回调中调用它。如果你这样做,你甚至不需要两个JavaScript文件。

请勿尝试通过超时或加载订单来管理此操作。这不是故障保险。您无法知道浏览器加载内容所需的确切时间。例如,如果您使用非常慢的互联网连接怎么办?不要试图预测那些事情,这就是回调的内容: - )

你的代码看起来像这样:

function doSthWithLoadedContent() {
    // whatever secondary.js tries to do
}

$.ajax({
        url: 'content.php',
        success: function(output){
            $('#dynamic-content').html(output);
            doSthWithLoadedContent();
        }       
});

答案 1 :(得分:0)

一旦将输出应用于html标记,您就可以使用 // DownloadJSON AsyncTask private class DownloadJSON extends AsyncTask<Void, Void, Void> { @Override protected void onPreExecute() { super.onPreExecute(); // Create a progressdialog mProgressDialog = new ProgressDialog(MainActivity.this); // Set progressdialog title mProgressDialog.setTitle("Load orders from server"); // Set progressdialog message mProgressDialog.setMessage("Loading..."); mProgressDialog.setIndeterminate(false); // Show progressdialog mProgressDialog.show(); } @Override protected Void doInBackground(Void... params) { // Create an array arraylist = new ArrayList<HashMap<String, String>>(); // Retrieve JSON Objects from the given URL address jsonobject = JSONfunctions.getJSONfromURL("http://www.xxxxxx.com/restaurant/ecommerce/api/orders.php?accesskey=12345"); try { // Locate the array name in JSON jsonarray = jsonobject.getJSONArray("orders"); for (int i = 0; i < jsonarray.length(); i++) { jsonobject = jsonarray.getJSONObject(i); GroupItem item = new GroupItem(); GroupItem itemdone = new GroupItem(); if(jsonobject.getInt("Status")==0){ item.title = jsonobject.getString("name"); item.tabletitle = jsonobject.getString("table_"); item.order_id= jsonobject.getString("id"); item.status_="0"; String str_order=jsonobject.getString("order_items_title"); StringTokenizer result_ = new StringTokenizer(str_order,"||"); while (result_.hasMoreTokens()) { String[] order_price=result_.nextToken().split("\\*"); ChildItem child = new ChildItem(); child.title =order_price[0]; child.hint = order_price[1]; item.items.add(child); } ChildItem child = new ChildItem(); child.title =jsonobject.getString("note"); item.items.add(child); items.add(item); }else if(jsonobject.getInt("Status")==1){ item.status_="1"; itemdone.title = jsonobject.getString("name"); itemdone.order_id= jsonobject.getString("id"); itemdone.tabletitle = jsonobject.getString("table_"); String str_order=jsonobject.getString("order_items_title"); StringTokenizer result_ = new StringTokenizer(str_order,"||"); while (result_.hasMoreTokens()) { String[] order_price=result_.nextToken().split("\\*"); ChildItem child = new ChildItem(); child.title =order_price[0]; child.hint = order_price[1]; itemdone.items.add(child); } ChildItem child = new ChildItem(); child.title =jsonobject.getString("note"); itemdone.items.add(child); itemsdone.add(itemdone); } } } catch (JSONException e) { Log.e("Error", e.getMessage()); e.printStackTrace(); } return null; } @Override protected void onPostExecute(Void args) { adapter = new ExampleAdapter(MainActivity.this); adapter.clear(); adapter.setData(items); listView = (AnimatedExpandableListView) findViewById(R.id.listView); listView.setAdapter(adapter); adapterdone = new ExampleAdapter(MainActivity.this); adapterdone.clear(); adapterdone.setData(itemsdone); listViewdone = (AnimatedExpandableListView) findViewById(R.id.listViewdone); listViewdone.setAdapter(adapterdone); // In order to show animations, we need to use a custom click handler // for our ExpandableListView. listView.setOnGroupClickListener(new OnGroupClickListener() { @Override public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) { if (listView.isGroupExpanded(groupPosition)) { listView.collapseGroupWithAnimation(groupPosition); } else { listView.expandGroupWithAnimation(groupPosition); } return true; } }); listViewdone.setOnGroupClickListener(new OnGroupClickListener() { @Override public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) { if (listViewdone.isGroupExpanded(groupPosition)) { listViewdone.collapseGroupWithAnimation(groupPosition); } else { listViewdone.expandGroupWithAnimation(groupPosition); } return true; } }); //////////////////////////////// mProgressDialog.dismiss(); } } private static class GroupItem { String title; String order_id; String tabletitle; String status_; List<ChildItem> items = new ArrayList<ChildItem>(); } private static class ChildItem { String title; String hint; } private static class ChildHolder { TextView title; TextView hint; } private static class GroupHolder { TextView title; CheckBox checkBox; public TextView tabletitle; } 加载脚本:

$.getScript

https://api.jquery.com/jquery.getscript/

答案 2 :(得分:0)

实现此目的的最佳方法实际上是将回调交给执行ajax调用的函数。我可能不会把它放在html中,但它演示了方法:

<html>
  <head>
    <script type="text/javascript" src="js/main.js"></script>
    <script lang="javascript>
      function doWhenLoaded(someCallback)
      {
        $.ajax({
          url: 'content.php',
          success: function(output){
            $('#dynamic-content').html(output);
            someCallback();
          }       
        });
      }

      $(document).ready(function(){
        doWhenLoaded(function(){
          $.getScript('js/secondary.js');
        });
      })

    </script>
  </head>
  ...
</html>

您也可以使用$.getScript加载secondary.js而不是使用main.js,并将其包装在函数调用中(即doStuff = function() { /* your code here */ })。然后,您可以在doWhenLoaded(doStuff)中致电$(document).ready

答案 3 :(得分:0)

您必须在ajax调用后添加脚本。

   $.ajax({
            url: 'url of ajax',
            type: "POST",
            data: data,
            dataType: "html",
            success: function (data) {
                $('#instructions').html('<div>' + data + '</div>');
                $.getScript("js/html5lightbox/html5lightbox.js", function() {
                    $('body').find('.html5lightbox').html5lightbox();
                });
            }

        });