与php无法在子目录中工作的ajax连接
Hello I have a javascript file in the directory
root/ assets/ js / a.js
and a php file at the directory
root/php/foo.php
At the a.js file I am trying to use ajax in order to connect with the foo.php . If the a foo.php is located at the root directory a.k.a
root/foo.php
the function works fine but when i put the file in the directory above nothing works. Here is the function associated with the connection
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
alert(xmlhttp.responseText);
}
}
xmlhttp.open("GET","../../studentSignupPHP/test.php?q=" + str, true);
The relative path at the
xmlhttp.open(..)
seems fine to me,so I cannot understand what I am doing wrong. Can you help me?
foo.php
<?php echo "test"; ?>
Rather than traversing from the js directory, use a reference to the root path like so
/php/foo.php
See charlietfl's comment above for the reason why.
Edit: Updated with comments from @charlietfl
"the path is dependent on the page you are loading in browser, not where the js file is stored. Open your browser dev tools and look at network tab, will see the path browser is trying to use for the ajax call"