使用Jquery为ajax请求设置基本URL的最佳方法是什么?

Ale*_*rov 9 ajax jquery cordova

由于phonegap基于本地html文件,因此它不知道远程服务器的基本URL.我想知道使用jquery为ajax请求设置基本URL的最佳方法是什么?有人可以提供样品的链接吗?

目前我考虑使用jquery ajax prefilter.

sam*_*lux 34

这样做的语义正确方法是使用<base>标记:

<head>
    <base href="http://mydomain.com/">
</head>
Run Code Online (Sandbox Code Playgroud)

然后像这样检索值(遗憾的是jQuery.ajax()不会自动获取此值):

$('head base').attr('href');
Run Code Online (Sandbox Code Playgroud)

元素参考:http://www.w3.org/TR/html4/struct/links.html#edef-BASE


use*_*274 26

两个既定答案都有很大的缺点.每次发出请求时都要求调用一个函数来按下你的URL是很多额外的输入.向页面添加基本标记在大多数情况下都可以正常工作,但如果您正在使用SVG进行繁重的工作,则会导致一些麻烦.这是一个简单的解决方案,可以在不使用基本标记的情况下立即修复所有网址.

var baseUrl = 'http://my.hardcoded.url/';
$.ajaxSetup({
    beforeSend: function(xhr, options) {
        options.url = baseUrl + options.url;
    }
})
Run Code Online (Sandbox Code Playgroud)

  • 我喜欢这个想法,但是这个方法应该检查options.url是否有根.否则,根网址将更新为无效网址 (3认同)
  • 这是一个隐藏的答案宝石.如果您正在处理您无法控制$ .ajax调用的遗留代码,那就太棒了 (2认同)

gha*_*yes 14

当我处理这个问题时,我只是把这些信息作为数据元素放在标签上.

 <body data-base="http://mydomain.com"> ...
Run Code Online (Sandbox Code Playgroud)

然后用它来构建给定请求的正确URL:

 //If pathOrURL is a relative path (e.g. /users/1), then we return a qualified
 // URL, such as http://mydomain.com/users/1
 // otherwise, we return the URL as is
 var qualifyURL = function(pathOrURL) {
   if (!(new RegExp('^(http(s)?[:]//)','i')).test(pathOrURL)) {
     return $(document.body).data('base') + pathOrURL;
   }

   return pathOrURL;
 };

 //Use this helper function when calling $.ajax
 $.ajax({
   url: qualifyURL(url), ... });
Run Code Online (Sandbox Code Playgroud)

这对我使用Phonegap的体验非常有用.希望这会有所帮助.