从html页面调用文件jQuery文件

时间:2013-09-09 15:59:27

标签: javascript jquery html ajax

我创建了一些使用Ajax刷新/更新两个字段的测试代码。它很棒 现在,为了保持整洁,我创建了一个名为Ajax.js的文件

在我的所有字段都在的HTML页面中,我想调用此文件并进行更新 这两个变量。

我做了以下事情:

在我的HTML页面中:

  <--- included the meta lines needed for the Ajax file ---->
  <--- included: my jQuery includes needed ---------->
  <---- my link to the Ajax.js file -------------->
 <script src="Ajax.js"></script>

 <----- made the call this way, I am not sure is right ------->
 <!----- Ajax Update Fields Function ----->
 <script>
   jQuery('nav').Ajax();
 </script>

呼叫不起作用,它不会更新字段。这是实际的Ajax.js代码:

// JavaScript Document
<script src="http://code.jquery.com/jquery-1.10.2.js"></script> 


$(function()
{
  setInterval(function()
   {
$.get("ajax_v00.html",function(data,textStatus, jqXHR)
 {
  var temperature=$(data).filter('#variable1').text()
  var time=$(data).filter('#variable2').text()
  $('#variable1').text(temperature)
  $('#variable2').text(time)
 })
 .fail(function(jqxhr,textStatus,errorThrown) //Callback failed
  {
   $('#errors').text("Errors:" + textStatus + " " + errorThrown)
  })
 .done(function() //Callback succeeded
  {
   $('#errors').text('Errors:');
  })
   },1000);
})

我该如何正确调用?希望我能正确解释自己吗?

2 个答案:

答案 0 :(得分:2)

把它放在你的html页面的头部......

<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script type="text/javascript" src="Ajax.js"></script>

Ajax.js删除脚本代码。

删除jQuery('nav').Ajax();你不需要这个。它正在寻找一个名为Ajax()的jQuery函数,它不存在。 Ajax.js中的代码已经在页面加载时运行,因为您已将其包装在document.ready的简写版本中...

$(function() {
    setInterval(function() {
        $.get("ajax_v00.html",function(data,textStatus, jqXHR) {
            var temperature=$(data).filter('#variable1').text();
            var time=$(data).filter('#variable2').text();
            $('#variable1').text(temperature);
            $('#variable2').text(time);
        })
        .fail(function(jqxhr,textStatus,errorThrown) {
            $('#errors').text("Errors:" + textStatus + " " + errorThrown);
        })
        .done(function() {
            $('#errors').text('Errors:');
        })
    },1000);
});

答案 1 :(得分:0)

请使用此脚本。

   <script>
    $(document).ready(function() {
                      jQuery('nav').Ajax();});
  </script>