-
Notifications
You must be signed in to change notification settings - Fork 114
Dev.Front Ajax
nothing edited this page Jul 16, 2013
·
9 revisions
- All AJAX/JSON calls should return an array as result
return array(
'status' => 1, // 1 for success, 0 or negative for failure
'message' => __('The operation is succeeded.'), // Optional
'data' => array(), // Optional
);
- get
// it will request '/article'
$.get('/article').done(function(res) {
});
// it will request '/article?page=1&num=10'
$.get('/article', {
page: 1,
num: 10
}).done(function(res) {
// res will be string, so you should parse it with function
res = $.parseJSON(res);
...
});
$.getJSON('/article', {
page: 1,
num: 10
}).done(function(res) {
//res will be json object
});
- post
// it will post '/session' with 'username password remember' data
$.post('/session', {
username: 'username',
password: 'password',
remember: 1
}).done(function(res) {
res = $.parseJSON(res);
if (res.status) {
//login success
} else {
//login fail
}
});
RESTful ajax
- get
var Module = Backbone.Model.extend({
urlRoot: '/module'
});
var systemModule = new Module({
id: 1,
title: 'system'
});
// it will request '/module/1' to get data
systemModule.fetch()
- post
var Module = Backbone.Model.extend({
urlRoot: '/module'
});
var systemModule = new Module({
title: 'system'
});
// it will request post '/module' to tell server to save data
systemModule.save();
- delete
var Module = Backbone.Model.extend({
urlRoot: '/module'
});
var systemModule = new Module({
id: '1',
title: 'system'
});
// it will request delete '/module/1' to tell server to delete data
systemModule.destroy();
- put
var Module = Backbone.Model.extend({
urlRoot: '/module'
});
var systemModule = new Module({
id: '1',
title: 'system',
version: '0.0.0'
});
// it will request put '/module/1' to tell server to edit data, but the client will send all attribute to server.
// If instead, you'd only like the changed attributes to be sent to the server, you can use patch
systemModule.save();
-
patch
Note: pi maybe not support this http method now
var Module = Backbone.Model.extend({
urlRoot: '/module'
});
var systemModule = new Module({
id: '1',
title: 'system',
version: '0.0.0'
});
// it will request patch '/module/1' with only `title` attribute to tell server to save the `title`
systemModule.save({
title: 'system1'
}, {
patch: true
});
skill: if your server donot support patch
method, you can use put to replace it like next code
var Module = Backbone.Model.extend({
urlRoot: 'module'
});
var systemModule = new Module({
id: '1',
title: 'system',
version: '0.0.0',
name: 'system'
});
// it will request put '/module/1' to tell server to edit data
systemModule.save({
title: 'system1',
version: '0.0.1'
}, {
data: 'title=system1&version=0.0.1' // changed attributes to be sent to the server
});