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 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥15 (关键词-阻抗匹配,HFSS,RFID标签天线)
  • ¥15 机器人轨迹规划相关问题
  • ¥15 word样式右侧翻页键消失