JQuery: how to replace hard-coded url for the hosted page?
I have this:
$("input.fetchData").click(function () {开发者_开发技巧
path = "/data";
var dataurl = 'http://localhost:8000' + path;
...
It works locally but when I deploy to my server it stops working. I want to replace localhost with the host that served the page. How?
You can use window.location
to get the information, but do you really need a full path? For ajax requests and such, a relative path should be sufficient. For instance:
$("input.fetchData").click(function () {
$.ajax({
url: "/data",
...
});
});
Fetches If page served from ------- ---------------------- http://localhost:8000/data http://localhost:8000 http://w3.example.com/data http://w3.example.com
...etc. If you want to fetch from a peer of the current location, you may find you want ../data
rather than /data
, which will always start at the root of the server.
Regardless, if you need a full path, here's a précis of location
properties:
protocol
- E.g.,http
orhttps
hostname
- The hostnameport
- The port (80 is the default, but of course it could be 8000 as in your question)host
-hostname
andport
pre-combined for you
...and then you may or may not want pathname
.
You can use "window.location" to know your host
You should have a look at the window.location
object, it has properties such as window.location.host
which you could use to construct the URL, such as:
$("input.fetchData").click(function () {
path = "/data";
var dataurl = 'http://' + window.location.host + path;
// ...
});
You can use relative rather than absolute URLs, or you can go through the window.location members in the DOM.
Relative URLs should work in most cases, but if they don't you can always re-create your URL with something like:
var curUrl = document.location.protocol + "//" + document.location.host + document.location.pathname;
精彩评论