I created some test code that uses Ajax to refresh/update two fields. It works great and now, to keep things neat, I have created a file called Ajax.js
In my HTML page where all my fields are, I would like to call this file and make it update the two variables.
I did the following:
In my HTML page:
<--- 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>
The call doesn't work, it doesn't update the fields. Here is the actual Ajax.js code:
// 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);
})
How can I call this properly? Hopefully, I explained myself correctly?
Put this in the head of your html page...
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script type="text/javascript" src="Ajax.js"></script>
Remove the script tags from Ajax.js
.
Remove jQuery('nav').Ajax();
You don't need this. It's looking for a jQuery function called Ajax()
, which does not exist. Your code in Ajax.js
will already run when the page is loaded as you have wrapped it in the shorthand version of 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);
});
Please use this script.
<script>
$(document).ready(function() {
jQuery('nav').Ajax();});
</script>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.