Convert ajax relative paths to absolute paths with

2019-09-02 20:04发布

问题:

I am working with codeigniter and jquery ajax. I'm having some incosistencies b/w my app locally on wamp (working perfectly) and my deployed app (not so much). Once possible suggested fix is to convert ajax relative paths to absolute paths for ajax, so it looks like:

url: "YOURBASEPATH/AjaxController/update",
location.href = "YOURBASEPATH/pan_controller/my_detail";

Here's my code right now:

$.ajax({a
     type: "POST",
     url: "AjaxController/update",
     data:{ i : searchIDs, m : message },                        
     dataType: 'json',
     .done(function() { 
          alert("REFRESHING..");
          location.href = "pan_controller/my_detail";
     });
   }
})

I have been using https://philsturgeon.uk/blog/2009/09/Asset-handling-in-CodeIgniter-with-the-BASE-tag for some time. Is this the same thing as having the base url hardcoded in ? if not how should I do this here without messing up other routes and the ability to deploy which are the advantage of relative routes.

回答1:

In your header section just add the following script.

<script type="text/javascript">
    var BASE_URL = "<?php echo base_url();?>";
</script>

Then in your Ajax code use BASE_URL as a variable. Means:

url: BASE_URL+"AjaxController/update", location.href = BASE_URL+"pan_controller/my_detail";

$.ajax({a
     type: "POST",
     url: BASE_URL+"AjaxController/update",
     data:{ i : searchIDs, m : message },                        
     dataType: 'json',
     .done(function() { 
          alert("REFRESHING..");
          location.href = BASE_URL+"pan_controller/my_detail";
     });
   }
})

Very simple solution.