views:

38

answers:

1

I use jquery ajax method, set datatype json, I get a jsonp response from a cross-domain server. But what i want is raw string of json response. so i set datatype text, but i got nothing but a empty string.

      $.ajax({
        url:"http://api.douban.com/book/subject/isbn/9787802057388?alt=xd&callback=?",
        dataType:'text',
        success:function(data){
            alert(data);
        } //endof success
    }); //endof .ajax

can any one tell me why? if use getJSON method to do this, how can i get a raw string of json?

A: 

Setting the dataType to text prevents jQuery handling the request as a JSONP. jQuery does some magic in the background for these type of requests (substituting callback=? in the URL for a function name, and defining the success function as a global function).

Why do you want the response to be raw text? It isn't possible to get a response that is just JSON from a JSONP request, because the nature of JSONP requires the response is wrapped in a function call.

Setting the dataType to jsonp works, but of course an object is returned.

$.ajax({
    url:"http://api.douban.com/book/subject/isbn/9787802057388?alt=xd&callback=?",
    dataType:'jsonp',
    success:function(data){
        alert(data);
    } //endof success
}); //endof .ajax​​​​

If you want a string, you could double-json-encode a part of the response on the server, so that it is received as a string, or use a JavaScript JSON encoder on the client and encode it again, but both don't really seem ideal solutions. An object is much more usable and useful.

Matt
the reason is i want get a cross-domain jsonp response and sent it to my web server again.To avoid jquery handle response as json, i change .getJSON to .ajax, so do you mean jquery ignore datatype field to handle the respons?
elprup
@elprup: In which case, the client should AJAX your server, who should retrieve the information from the remote domain, before returning a response. No, I mean that jQuery needs the `dataType` set to `jsonp` to correctly prepare the request to act as a `JSONP` request.
Matt
OK. The url I request has limit on request per IP, so i just want client to fetch the infomation for the server.
elprup