views:

38

answers:

1

I'm talking to a server and the JSON response looks like this:

someResponse({ "Response":{"status":"3","message":"Not valid bla bla"} });

Proper JSON should look like this, right?:

{
    "response":
    {
        "status":"3",
        "message":"Not valid bla bla"
    }
}

Is there a way I could somehow reach that data with jQuery if enclosed in that "someResponse" function?

My jQuery code looks like this:

$.ajax({
   url: "https://someurl/test/request.asp?user=x&pass=x",
   dataType: "JSONP",
   success: function(msg){
    $("#json_here").html(msg.response.status);
   },
   error:function(x,e){alert(x+" :: "+e)}
});

Of course, nothing happens when I do that. But if i do $("#json_here").html(msg); then I ges the full response as above.

Am I doing something wrong or is this an invalid way of sending JSON data? I'm not getting parse errors.

Thanks in advance.

+5  A: 

The server returns JSONP, not JSON. This is done to facilitate cross-domain requests (in other words ajax mashups).

All you need to do is implement a function called someResponse to parse the answer and insert the loaded response into your page. Your someResponse will then be called automatically by the browser. You could also have a look at one of the many tutorials on JSONP.

Often times APIs returning JSONP allow the client to choose a name for the function that should be called with the loaded JSON. So you can rename your handler as you want, you just need to tell the server about it.

Adrian Grigore
Thanks very much Adrian. I obviously didn't know how to deal with a JSONP response. I understood how the JSONP request works but I didn't know it returned a function. I was expecting regular JSON back.Anyway, I still can't figure out where to construct the function with jQuery. I've seen examples of this with regular Javascript but I cannot seem to make it work with jQuery. If I construct the function inside the success function it won't work, of course. If I do it outside of it, which I did, it didn't work either. Does anyone have an example?Thanks again.
@user435131: This doesn't have anything to do with the way you are making the request (jQuery in this case). You just need to define a global function that has the same name as the function call returned by the server. If that doesn't work, start Firebug and try to find any javascript errors. Or analyze the server output if there aren't any. It shouldn't be too hard to debug this.
Adrian Grigore