如何使用JavaScript访问不同目录中的.php文件?

To start with, this question might already have an answer, but I have been searching all day, but I could not find a workout that helped me with my exact problem.

I am new to JavaScript and AJAX

I am trying out a web app, named calendar.php in the directory C:\xampp\htdocs\projects\aptana\testapp\. This has a script named calendar_script.js in the directory C:\xampp\htdocs\projects\aptana\testapp\scripts\. The calendar_script.js has a function getDetails()

//--function to get the details from the server--
function getDetails(dateName){
     request = createRequest();

     if(request == null){
         alert("Undable to create request. Please Check Internet Connection or contact service Administrator.");
         return;
     }

     var url = "getEvents.php?dateID=" + escape(dateName);
     request.open("GET", url, true);
     request.onreadystatechange = displayDetails;
     request.send(null);
 }

The createRequest() function returns a request object. The getDetails() function is called when there is a click event on the web page, which is a calendar.

The problem is with the getEvents.php. If it is placed in the directory C:\xampp\htdocs\projects\aptana\testapp\ everything seems to work just fine, but if I move this file to another folder, which is C:\xampp\htdocs\projects\aptana\testapp\internals\ and try to access the file by creating a file path in my JavaScript code, it does not seem to work. I tried doing

var base_url = window.location.origin + "\projects\aptana\testapp\internals\";
var url = base_url + "getEvents.php?dateID=" + escape(dateName);
request.open("GET", url, true);

it does not seem to work. I also tried hard coding the entire file path : C:\xampp\htdocs\projects\aptana\testapp\internals\ but it doesn't seem to work either.

I know I am doing a mistake and I am missing something. How can I solve this problem? Please help. Thank you in advance.

So you have the script in testapp/ and the php in testapp/internals/. I think you have to use something like this:

var url = "internals/getEvents.php?dateID=" + escape(dateName);
request.open("GET", url, true);

Please note the / instead of \.

  • Use / instead of \.
  • Use relative instead of absolute paths (here your root directory is C:\xampp\htdocs\projects\aptana\testapp).

Your code:

var url = "internals/getEvents.php?dateID=" + escape(dateName);
request.open("GET", url, true);
request.onreadystatechange = displayDetails;
request.send(null);

Change

var base_url = window.location.origin + "\projects\aptana\testapp\internals\";

Into

var base_url = "projects/aptana/testapp/internals/";