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 nginx无证书访问https失败
  • ¥15 树莓派启动AP热点传入数据
  • ¥15 multisim中关于74ls192n和DSWPK开关的问题(相关搜索:计数器)
  • ¥15 在误装Windows server2019 后如何利用Windows.old恢复?
  • ¥20 代码实现状态连接包过滤防火墙的设计与实现
  • ¥15 vscode的红色箭头爆红和has no default export报错
  • ¥15 关于#sql#的问题:#情况描述 在用vs对项目进行调试时,出现找不到网络路径,然后查看SQL配置工具,发现SQL服务显示远程调用过程失败(相关搜索:防火墙)
  • ¥15 eNSP中基于默认路由及浮动路由的公司与分部互联和校园网综合项目
  • ¥15 主要进行描述泥浆在管路不同区段泥浆的密度不相同,泥浆的密度有高有低,此时管路的摩阻分布需要怎么计算,(标签-matlab)