beim googlen nach "jQuery rest" kommt man nicht um das Script vom "Sasa Jovancic" vorbei, daher habe ich mir erlaubt sein Script als Vorlage zu nehmen und es zu erweitern.
Für dieses Beispiel wird eine funktionieren tastypie-Anwendung benötigt wie z.b. hier.
In der Standartkonfiguration ist die default "Authentication" eingestellt, also keine.
Als autorisation ist "DjangoAuthorization" eingestellt, also kann man nur Anfragen absetzen wenn man sich eingeloggt hat
Hier die JS-Klasse
Danke an Sasa Jovancic für diesen Code-Snippets
/* JS REST.js */
function RestServiceJs(newurl) {
this.myurl = newurl;
this.add = function(model, callback) {
console.log(JSON.stringify(model));
$.ajax({
type : 'POST',
url : this.myurl,
data : JSON.stringify(model), // '{"name":"' + model.name + '"}',
dataType : 'text',
processData : false,
contentType : 'application/json',
success : callback,
error : function(req, status, ex) {
},
timeout : 60000
});
};
this.update = function(model, callback) {
$.ajax({
type : 'PUT',
url : this.myurl,
data : JSON.stringify(model), // '{"name":"' + model.name + '"}',
dataType : 'text',
processData : false,
contentType : 'application/json',
success : callback,
error : function(req, status, ex) {
},
timeout : 60000
});
};
this.findById = function(id, callback) {
$.ajax({
type : 'GET',
url : this.myurl + id,
contentType : 'application/json',
success : callback,
error : function(req, status, ex) {
},
timeout : 60000
});
};
this.filter = function(query, callback) {
$.ajax({
type : 'GET',
url : this.myurl + "?" + $.param(query),
contentType : 'application/json',
success : callback,
error : function(req, status, ex) {
},
timeout : 60000
});
};
this.findAll = function(callback) {
$.ajax({
type : 'GET',
url : this.myurl,
contentType : 'application/json',
success : callback,
error : function(req, status, ex) {
},
timeout : 60000
});
};
this.remove = function(id, callback) {
$.ajax({
type : 'DELETE',
url : this.myurl + id,
contentType : 'application/json',
success : callback,
error : function(req, status, ex) {
},
timeout : 60000
});
};
this.loadTmpl = function(turl, callback) {
$.ajax({
url : turl,
success : callback,
error : function(req, status, ex) {
},
timeout : 60000
});
}
}
Die REST.js und natürlich jQuery binden wir ein und los geht's.
Nach dem die Seite geladen ist können wir gleich mit der Browser-Konsole spielen.
p = new RestServiceJs("/api/v1/poll/") // mit slash am ende, da sonst kein POST von django akzeptiert wird
// fetche alle Daten
r.findAll(function(data){
console.log(data);
})
// fetch by id
r.findById(1, function(data){
console.log(data);
})
// django filter mit (i)startswith, (i)endswith, (i)contains, gt, lt ...
r.filter(
{ bezeichnung__istartswith:'1008'},
function(data){
console.log(data);
})
beim filter kann django-db-filter-notation verwendet werden.
also viel spaß beim ausprobieren!