从 html 页面调用文件 jQuery 文件

calling a file jQuery file from html page

本文关键字:文件 jQuery 调用 html      更新时间:2023-09-26

我创建了一些使用 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);
})

我怎样才能正确地调用它? 希望我解释正确吗?

把它放在你的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);
});

请使用此脚本。

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