duanhuizhe6767
duanhuizhe6767
2017-05-14 12:00
浏览 277

在AJAX中获取当前的网站域名

I have a quick question regarding AJAX requests and Posts.

Let's say I have a website called www.mysite.com and I make this AJAX post:

$.ajax({
type: "POST",
url: 'www.mysite.com/post.php',
data: {msg:"Hello world"},
cache: false,
success: function(response){
    alert(response);
}

Ok now this works perfectly fine, but let's say I wanna change my domain name, to something more exciting, like www.myamazingwebsite.jeff I'd need to replace that URL in every AJAX request/post I ever made. That can become very annoying.

Isn't there a variable like %CurDomain or %CurPath to get the current domain name or the current path to the JS file the AJAX post is being made in?

That would allow me to NOT change those URLs

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dongxiao1591
    dongxiao1591 2017-05-14 12:07
    已采纳

    Use document.location.hostname for the domain and document.location.pathname for the path.

    document.location.href can get the full URL.

    So corresponding to your code:

    $.ajax({
    type: "POST",
    url: document.location.href,
    data: {msg:"Hello world"},
    cache: false,
    success: function(response){
        alert(response);
    }
    
    点赞 评论
  • dongxuanyi3406
    dongxuanyi3406 2017-05-14 12:14

    You may try this. In a separate js file say mysite.js, write var mysite="www.myamazingwebsite.jeff/"; Now include this file in all the js files making ajax calls as within your $.ajax({... write url: mysite + 'post.php', so next time to change your domain name just change mysite in the mysite.js as mysite="www.mynesitename.jeff/"

    点赞 评论

相关推荐