Trouble getting a valid response from a webservice
I am currently developing a web-frontend for a web service. I am using jQuery 1.5.1 as JS-Framework and Firebug for debugging purpose.
First of all, I have tested the web service with the Firefox Extension "REST Client". There, the following Request is successful:
{"requestUrl":"http://localhost:8080/Foobar/rest/goods?label=Schro","requestMethod":"GET","requestBody":"","headers":["accept","application/json"]}
Now, I want to reproduce this request in the context of a jQuery UI autocomplete() method:
$("#autocompleteTest").autocomplete({
source: function( request, response ) {
$.ajax({
url: "http://localhost:8080/Foobar/rest/goods/",
dataType: "json",
data: {
label: $("#autocompleteTest").val()
},
headers: {'accept':'application/json'},
error: function(jqXHR, textStatus, errorThrown) {
log(textStatus + "," + errorThrown);
log(jqXHR);
},
success: function( data ) {
console.log("bla:" + data);
response( $.map( data, function( item ) {
return {
label: item.label + " # " + item.id,
value: item.id
}
}));
}
});
},
// [...]
I took this recipe from the jQuery UI autocomplete demo
However, this triggers the error-event. Firebug says:
GET http://localhost:8080/Foobar/rest/goods/?label=Schrott - 200 OK 16ms
Antwort-Header
Server Foobar-Optimizer
Content-Type application/json;charset=UTF-8
Transfer-Encoding chunked
Date Wed, 09 Mar 2011 10:50:03 GMT
Anfrage-Header
Host localhost:8080
User-Agent Mozilla/5.0 (Windows NT 6.1; WOW64; rv:2.0b12) Gecko/20100101 Firefox/4.0b12
Accept application/json
Accept-Language de-de,de;q=0.8,en-us;q=0.5,en;q=0.3
Accept-Encoding gzip, deflate
Accept-Charset ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive 115
Connection keep-alive
Origin null
The error jqXHR says:
[Object { readyState=0, status=0, statusText="error"}]
and the response Header is empty.
Both requests look identical in my eyes aside from the different results. I would appreciate any suggestions. Thank you.
Update: Solution
This is a cross-domain policy issue. I wasn't aware about this behaviour. The solution is to change the $.ajax datatype from "json" to "jsonp". This is an elegant method to override these policies and to access remote web-开发者_如何学JAVAservices.
Of course, the web service has to be able to handle this json "padding".
A bunch of other possibilities is mentioned here: http://usejquery.com/posts/9/the-jquery-cross-domain-ajax-guide
I can answer this question on my own: This is a cross-domain security policy issue. I wasn't aware of this behaviour.
The following link contains a bunch of applicable approaches:
http://usejquery.com/posts/9/the-jquery-cross-domain-ajax-guide
精彩评论