JQuery Ajax url

I am making an Ajax call from site.com/users/{username}

I want to access the site.com/account/deleteComment URL , but when I check firebug it tries to access site.com/users/account/deleteComment

here is my code

    $.ajax({
        url: "../account/deleteComment/" + deleteID,
        success: function () {
            $("#comment-" + deleteID).slideUp("fast");
        }
    });
+5
source share
5 answers

Well then ../../going to do the trick, right?

However, it would be nice to use absolute URLs here.

  url: "/account/deleteComment/" + deleteID,

this will remove your ability to easily move your application to a subfolder, but in most cases this is not a problem.

+14
source

Change the url to:

/account/deleteComment/

Thus, it will go to the root path:

site.com/account/deleteComment
+1

.
, ,

$.url("Config/GetEnvironment")

, URL-, .

+1

An absolute URL is a good idea in ajax, but it is a nicer and easier way. Just declared var siteURL = www.example.com;globally. And used it in every request ajax, as shown below.

<script>
$.ajax({
    url: siteURL + '/path/to/file',
    type: 'POST',
    data: {param1: 'value1'},
});
</script>

As a rule, I declared in the main index file or configuration of the JS file.

0
source

you can use location.origin to get the base address

var deleteID;
 $.ajax({
        url:location.origin + "/account/deleteComment/" + deleteID,
        success: function () {
            $("#comment-" + deleteID).slideUp("fast");
        }
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Run codeHide result

 $.ajax({
        url:location.origin + "/account/deleteComment/" + deleteID,
        success: function () {
            $("#comment-" + deleteID).slideUp("fast");
        }
    });
Run codeHide result
0
source

All Articles