ajax类似请求URL问题?

比如下面angular这种url只写后半段

提交后如何生成前面这段地址的?

阅读 2.8k
4 个回答

跟angular无关。这个由浏览器完成
请求url不写绝对路径时候,规则如下:(以当前问题链接为例子)

页面链接 https://segmentfault.com/q/1010000010783953?_ea=2414431

$.ajax('/a.php') - 访问 https://segmentfault.com/a.php
$.ajax('a.php') - 访问 https://segmentfault.com/q/a.php

这个你是写的url是相对路径,所以最终提交时候应该angular会解析为绝对路径。

直接上代码,纯个人设计,你可以随意增删改,只是提供个思路

`$angular.factory("commonHeader", function () {

return "http://xx.xx.xx.xx:8081";

});

$angular.service("commonHttp", function ($http, $httpParamSerializer, commonHeader) {

this.url = "";
this.sendData = "";
this.request = function (successCallback, errorCallback) {
    if (typeof (errorCallback) != "function") {
        errorCallback = function () {
        };
    }
    if (!this.sendData){
        this.sendData = {};
    }
    
    $http({
        method: "POST",
        headers: {
            'Content-type': 'application/x-www-form-urlencoded'
        },
        url: commonHeader + this.url,
        data: $httpParamSerializer(this.sendData)
    }).then(function (response) {
        successCallback(response)
    }, errorCallback());
}

});`

`$angular.factory("XXXX", function (commonHttp) {

return {
    url : "/xx/xx",
    sendData: commonHttp.sendData,
    request: commonHttp.request
};

});`

关键字 interceptors

var app = angular.module('myApp', []);
 app.config(function ($httpProvider) {
     $httpProvider.interceptors.push(function ($q) {
         return {
             'request': function (config) {
                 config.url = 'http://localhost:8080/XVIEW/' + config.url;
                 return config || $q.when(config);
             }
         }
     });
 });

 app.controller('myCtrl', function ($scope,$http) {
     $http.get('stockpledge/UpdateStockpledge').success(function (data) { alert(data) }).error(function (fail) {

     });
 });
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
1 篇内容引用
推荐问题