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 onlyoffice编辑完后立即下载,下载的不是最新编辑的文档
  • ¥15 求caverdock使用教程
  • ¥15 Coze智能助手搭建过程中的问题请教
  • ¥15 12864只亮屏 不显示汉字
  • ¥20 三极管1000倍放大电路
  • ¥15 vscode报错如何解决
  • ¥15 前端vue CryptoJS Aes CBC加密后端java解密
  • ¥15 python随机森林对两个excel表格读取,shap报错
  • ¥15 基于STM32心率血氧监测(OLED显示)相关代码运行成功后烧录成功OLED显示屏不显示的原因是什么
  • ¥100 X轴为分离变量(因子变量),如何控制X轴每个分类变量的长度。