Question

For one site, Chrome and IE invoke ajax calls using urls without prepending javascript file directory to url.

html:

<!DOCTYPE html>
<html>
<head>
 <script src="/admin/pos.js?v=r2zPvjSAIOf2x8oTbPdUvRh9sFohBNwKM2QOVoOYSug1"></script>
.....

pos.js:

var xhr = $.ajax({
            url: '/api/Registers/Test',
            timeout: 3 * 1000,
            dataType: 'json',
            cache: false
        });

Application is running by typing http://1.2.3.4/admin/Sale in browser url.

Chrome console shows that ajax calls are invoked using wrong url:

http://1.2.3.4/api/Registers/Test?_=1393704244572

How to force browser to use correct url by prepending admin to url:

http://1.2.3.4/admin/api/Registers/Test?_=1393704244572

Code above works for some sites but stopped work for one site where ip address 1.2.3.4 was used without dns name as in other sites and application is mapped to site root directory. Application was changed as well and mono was upgraded to 3.2.8 No idea what caused browser to stop creating correct urls?

I'd prefer not to use base html element or use absolute url in javascript. Based on my understandig this code should work without them

ASP.NET MVC4 application is running in Mono 3.2.8 + mod_mono in Debian.

jquery is used.

Was it helpful?

Solution

Try to use the UrlHelper.RouteUrl method.

var xhr = $.ajax({
 url: '@Url.RouteUrl("Default", new { controller = "Registers", action = "Test" })',
 ...

EDIT: To generate the path to the javascript file you could use another helper:

<script src="@Url.Content("~/admin/pos.js")"></script>

EDIT2 Your best and probably the only solution is to pass the url as the js function's argument

Your function in pos.js:

function MyFunction(url)
{
  var xhr = $.ajax({
  url: url,
  ...
}

and then call it from the cshtml like:

MyFunction('@Url.RouteUrl("Default", new { controller = "Registers", action = "Test" })');
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top