0

When uploaded to a hosted server the following code is successfully turned to http://myexample.com/otherpartsofpath :

 ajax: {
        url: 'http://' + window.location.hostname + '/otherpartsofpath', 
        type: 'GET',
        ...

But when rendered on the local computer it gives an error. That's why in this case I should define the URL explicitly:

 ajax: {
        url: 'http://localhost:10930/otherpartsofpath', 
        type: 'GET',
        ...

How could I make the code to work locally without explicitly defined URL?

0

3 Answers 3

3

Using a relative path /test will always result in the correct protocol, hostname and port. Thus, for convenience you could just always use:

 ajax: {
        url: '/otherpartsofpath', 
        type: 'GET',
        ...

When run on http://test.com/directory/test.html it is http://test.com/otherpartsofpath.

When run on http://localhost:1234/directory/test.html it is http://localhost:1234/otherpartsofpath.

Sign up to request clarification or add additional context in comments.

Comments

1

You can't for security reasons.

Use a local server for testing. Set up a proxy if you want to fetch data from a remote server.

Comments

1

If you're not on port 80 locally you'll have to do something like

var hostName = window.location.hostname;
if ( window.location.port != '') {
    hostName += ':' + window.location.port;
}

and use that in your AJAX URL.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.