I want to refresh my MVC view using jquery.load and ajax after every 3 seconds. What will be the syntax for this? I used below code but it didn't work.
$(document).ready(function() {
setInterval(function() {
var url = '<%= Url.Action("Index", "LiveGame") %>';
$.getJSON(url, null, function() { });开发者_如何学运维
}
, 3000);
});
You should use load
or get
jQuery method. getJSON
return result in JSON format, while your view returns HTML.
Your code might be looking something like this:
$(document).ready(function() {
setInterval(function() {
var url = '<%= Url.Action("Index", "LiveGame") %>';
$('body').load(url);
}, 3000);
});
Of course it won't refresh anything - this is an ajax call after all. You must also implement the code that will take the values returned by the ajax method and place it dynamically into the view...
OR you do what @gor is suggesting you - which is NOT ajax btw.
Edit Let's suppose that your JSON data returns a name
field, and that there is an input text field in your view with ID = txtName
. So that's the (ajax) way to do it:
$(document).ready(function() {
setInterval(function() {
var url = '<%= Url.Action("Index", "LiveGame") %>';
$.getJSON(
url,
null,
function(data) {
$('#txtName').val(data.name);
}
);
},
3000
);
});
Please notice that you are NOT refreshing "the view" - you are individually refreshing each returned JSON value into their corresponding HTML elements. That's what's ajax is about - to be able to dynamically change values, using DOM manipulation, without loading a whole new page from the web server...
That also means that your server-side method should also return a valid JSON object.
This may sound like too much work - if that's the case, and you really just wanna refresh the page without dealing with asynchronous ajax calls and serializing JSON objects, just do what @gor is telling you to do, which means refreshing the whole HTML page each 3 seconds...
精彩评论