0

Using a GlassFish server running on port 8080, I can access http://localhost:8080/ws/ through my web browser.

But the webpage cannot be fetched using jQuery, $.ajax function:

$.ajax({
    url: "http://localhost:8080/ws/",
    type: "GET",
    success: function() {alert("good");},
    error: function() {alert("error");}
});

Every time, a message box with "error" is shown.

Here is what I captured using firebug:

enter image description here

But the response tag shows nothing:

enter image description here

Can anyone give me any suggestion about how to debug this?

NOTE:

  1. I have try to use error: function(request, status, error), but nothing useful is fetched.
  2. Using Wireshark to capture loopback HTTP packets, I can see that all the response is there, but not shown by firebug as illustrated above.
Yishu Fang
  • 9,448
  • 21
  • 65
  • 102
  • Is the web site doing the request also at localhost:8080? – JJJ Aug 06 '13 at 08:32
  • What do you want achive with your source code? Normally Ajax is used to send data. I cannot see that. – Reporter Aug 06 '13 at 08:32
  • No, that site is a localhost:80, @Juhana – Yishu Fang Aug 06 '13 at 08:35
  • Yes, I use that ajax code to send data, but it doesn't work. So I try to simplify it to a minimal set of code to see what's wrong. @reporter – Yishu Fang Aug 06 '13 at 08:36
  • possible duplicate of [How do I send an AJAX request on a different port with jQuery?](http://stackoverflow.com/questions/2099728/how-do-i-send-an-ajax-request-on-a-different-port-with-jquery) – JJJ Aug 06 '13 at 08:40

1 Answers1

2

You've said that the page you're running your jQuery code on is from "localhost:80", so that means you're running into the Same Origin Policy, which prevents cross-origin ajax calls. Port 80 and port 8080 are different origins for the purpose of the SOP.

Just for completeness, here's a list of what must be the same for two origins to match:

  • The protocol (so, file: vs. http: vs. https:, etc.)
  • The port
  • The server name (e.g., localhost, example.com vs. sub.example.com, etc.)

The origin is matched against the document (the HTML file containing the script tag), not the location of the script file itself.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • Then why we can access RESTful apis provided by Google using Javascript? – Yishu Fang Aug 08 '13 at 04:26
  • @UniMouS: If you're doing that via ajax, Google's servers must be using [CORS](http://www.w3.org/TR/access-control/) (and your browser must support it). – T.J. Crowder Aug 08 '13 at 07:35