Я бы порекомендовал использовать функциональность jQuery.extend (), чтобы упростить ваши вызовы и создать API javascript.Check проверить это видео из MVC Conf
Я использую стандартный вызов ajax, как это
//A standard ajax api call that takes in a set of options
//This uses the jQuery extend method to merge the supplied options with a set of defaults
(function ($) {
$.apiCall = function (options) {
var config = $.extend({
type: 'GET',
data: {},
contentType: 'application/x-www-form-urlencoded',
success: function () { },
error: function () { }
}, options);
$.ajax({
type: config.type,
url: config.url,
contentType: config.contentType,
data: config.data,
success: function (result) {
config.success(result);
},
error: function (result) {
config.error(result);
flashError('An error occured during the operation');
//Okay, so this last bit is kindof a problem. Your nice, sharable api should not be referencing something
// on the master page. So you could pass it all the way down. But that means you have to have this defined
// lots of places. Or you could create another js object to wrap this. There are several ways to do this and
// how you do it is up to you.
}
});
}
})(jQuery);
Затем я расширяю его с API для каждой сущности
//User api object
//Uses the prototype method to make sure all objects of this type have required functions
var patientsApi = function () { }
userApi.prototype.getUsers = function (options,Id) {
var config = $.extend({
success: function () { },
error: function () { }
}, options);
$.apiCall({
url: '/Users/GetUser',
data:{ID:Id},
success: function (result) { config.success(result); }
});
}
Затем вы можете позвонить со страницы, как это
var api = new userApi();
var UserId= $("#UserId").val();
api.getUsers({
success: function (result) {
//Do some stuff
}
},userId);