jQuery ajax call to REST service
Solution 1:
You are running your HTML from a different host than the host you are requesting. Because of this, you are getting blocked by the same origin policy.
One way around this is to use JSONP. This allows cross-site requests.
In JSON, you are returned:
{a: 5, b: 6}
In JSONP, the JSON is wrapped in a function call, so it becomes a script, and not an object.
callback({a: 5, b: 6})
You need to edit your REST service to accept a parameter called callback
, and then to use the value of that parameter as the function name. You should also change the content-type
to application/javascript
.
For example: http://localhost:8080/restws/json/product/get?callback=process
should output:
process({a: 5, b: 6})
In your JavaScript, you will need to tell jQuery to use JSONP. To do this, you need to append ?callback=?
to the URL.
$.getJSON("http://localhost:8080/restws/json/product/get?callback=?",
function(data) {
alert(data);
});
If you use $.ajax
, it will auto append the ?callback=?
if you tell it to use jsonp
.
$.ajax({
type: "GET",
dataType: "jsonp",
url: "http://localhost:8080/restws/json/product/get",
success: function(data){
alert(data);
}
});
Solution 2:
From the use of 8080 I'm assuming you are using a tomcat servlet container to serve your rest api. If this is the case you can also consider to have your webserver proxy the requests to the servlet container.
With apache you would typically use mod_jk (although there are other alternatives) to serve the api trough the web server behind port 80 instead of 8080 which would solve the cross domain issue.
This is common practice, have the 'static' content in the webserver and dynamic content in the container, but both served from behind the same domain.
The url for the rest api would be http://localhost/restws/json/product/get
Here a description on how to use mod_jk to connect apache to tomcat: http://tomcat.apache.org/connectors-doc/webserver_howto/apache.html