Relative reference in Javascript files

Asked

Viewed 161 times

0

Hello, Community!

My question is about how the reference to external files works in a Javascript file also external. 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 file index.php the reference to the archive json.php is lost, although it is technically correct to use the relative reference in the file .JS.

How does that explain?

  • Humn! We have one serial downvoter around here. I don’t mind that you deny the question, but at least justify it for the sake of other people’s judgment.

1 answer

1


I go through the same problem, created a function and put in my overall 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, regardless of the level the URL is.

url: getHostSite() + "Views/TelaCompras",
  • you can explain better what the code does?

  • 1

    It’s very simple, it takes your root URL, no directories or routes. So you don’t need to use ".. /data/json" and yes only getHostSite() + "data/json", ensuring it works, regardless of the level you are in your URL.

  • 1

    So that’s what I want!!!

  • Test this routine if you still have a one-touch problem! hugs

Browser other questions tagged

You are not signed in. Login or sign up in order to post.