views:

236

answers:

2

The whole day yesterday I've been trying to solve this but it's proven to be very challenging for me.

I'm trying to use this JS to get information from a java application I wrote.

$(document).ready(function() {
 $.getJSON('http://localhost/custest?callback=?', function(json) {
   alert('OK');
     $('.result').html(json.description);
  });     
 });

The Java application uses httpServer and is very basic.

When I access the page 'http://localhost/custest?callback=?' with Firefox, the browser shows me the server is sending me json data and asks with what to open it with, but when I try it from a webpage using the JS above it doesn't work. The getJSON call is not successful, the alert("ok") doesn't popup at all.

If it replace "http://localhost/custest?callback=?" in the JS with "http://twitter.com/users/usejquery.json?callback=?" everything works fine.

An interesting thing is that if I send malformed JSON from my java server Firebug gives an error and tells me what is missing from the JSON so that means the browser is receiving the JSON data, but when I send it a correct JSON string nothing happens, no errors, not even the alert() opens.

I'm adding the headers in case you think these could be relevant.

http://localhost/custest?callback=jsonp1274691110349

GET /custest?callback=jsonp1274691110349 HTTP/1.1
Host: localhost
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.3) Gecko/20100401 Firefox/3.6.3
Accept: */*
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 115
Connection: keep-alive

HTTP/1.1 200 OK
Transfer-Encoding: chunked
Content-Type: application/json

Thanks for your help.

+1  A: 

Are you returning JSON instead of JSONP? Try omitting the 'callback=?' part and see if that helps. The jQuery documentation has additional info on JSON vs JSONP. EDIT: The link to the documentation should be valuable as well: http://api.jquery.com/jQuery.getJSON/

nillls
That was the problem, I didn't send JSONP, I sent JSON. Works now. Thanks.
b2238488
A small click on the checkbox to the left of this comment wouldn't hurt.. ;)
nillls
+2  A: 

Is the page you are sending the AJAX request hosted on the same server as your Java application? If this is not the case is the callback=? parameter taken into account by your Java application? The reason this works with Twitter is that it sends JSONP, i.e. your server needs to send the data like this:

nameofcallback({ name: 'Smith' });

If both are hosted on the same domain you don't need the callback parameter.

Darin Dimitrov
Works now, thank you so much. The problem was I was sending JSON instead of JSONP.I do need this script to work cross domain actually.
b2238488