Ajax设置,基本网址

I have a lot of ajax calls in my project, so I configured my ajaxsetup to handle the errors by default and some other configs:

$.ajaxSetup({  error: function(result){ ....}});

Now all my ajax calls have an url, something like this:

$.ajax({
            url: 'http://localhost/controller/action',
            type: 'GET'           
        });

All these urls share this of course http://localhost, so my question is if I can configure the ajaxsetup so the base url is set by default and I just have to put the dynamic part of it in each call, so calls should look like this

$.ajax({
            url: '/controller/action',
            type: 'GET'           
        });

This would help when moving from dev to test or live as well

You can use $.beforeSend to manipulate the data before the request is made, such as changing the url on it.


Or you can get the base url dynamically in a central function like this

function getBaseUrl() {
var pathArray = location.href.split('/');
var protocol = pathArray[0];
var host = pathArray[2];
var url = protocol + '//' + host + '/';

return url;
}

And call like so...

$.ajax({
    type: "POST",
    url: getBaseUrl() + Controller + '/' + Action,
    contentType: "application/json; charset=utf-8",
    data: JSON.stringify({}),
    dataType: 'json',
    success: function (Result) {

    },
    error: function (Result, Status, Error) {
        console.log("Error: " + Error);
    }
});