weixin_33690367 2018-03-01 19:14 采纳率: 0%
浏览 48

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

  • 写回答

1条回答 默认 最新

  • lrony* 2018-03-01 19:36
    关注

    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);
        }
    });
    
    评论

报告相同问题?

悬赏问题

  • ¥15 在若依框架下实现人脸识别
  • ¥15 网络科学导论,网络控制
  • ¥100 安卓tv程序连接SQLSERVER2008问题
  • ¥15 利用Sentinel-2和Landsat8做一个水库的长时序NDVI的对比,为什么Snetinel-2计算的结果最小值特别小,而Lansat8就很平均
  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同