Relative reference in JavaScript files

0

Hello, Community!

My question is about how external reference to files works in an external JavaScript file. I explain!

Suppose I have three files: index.php , json.php and javascript.js with the following structure

/
    index.php
    js/
        javascript.js
    data/
        json.php

The JavaScript file has the following code, referencing the file json.php :

$.getJSON( "../data/json.php", function( data ) {
    //faz alguma coisa aqui
});

Now, if I include the JavaScript file in the index.php file, the reference to the json.php file gets lost, although the relative reference in the .JS file is technically correct.

How can this be explained?

    
asked by anonymous 07.12.2015 / 11:54

1 answer

1

I go through the same problem, I created a function and put it in my global script file in the project.

function getHostSite() {
  //identificar inicio do path
  //usada nas chamadas Ajax / jSON
  var Path = location.host;
  var VirtualDirectory;
  if (Path.indexOf("localhost") >= 0 && Path.indexOf(":") >= 0) {
    VirtualDirectory = "";
  }
  else {
    var pathname = window.location.pathname;
    var VirtualDir = pathname.split('/');
    VirtualDirectory = VirtualDir[1];
    VirtualDirectory = '/' + VirtualDirectory;
  }
  return location.protocol + "//" + location.host + VirtualDirectory + "/"
}

I use it for ajax calls, no matter what level the URL is.

url: getHostSite() + "Views/TelaCompras",
    
07.12.2015 / 12:12