使用jquery ajax方法获取原始json字符串遇到问题
我使用jquery ajax方法,设置数据类型json,我从跨域服务器得到jsonp响应。但我想要的是 json 响应的原始字符串。所以我设置了数据类型文本,但除了空字符串之外什么也没有。
$.ajax({
url:"http://api.douban.com/book/subject/isbn/9787802057388?alt=xd&callback=?",
dataType:'text',
success:function(data){
alert(data);
} //endof success
}); //endof .ajax
谁能告诉我为什么吗? 如果使用 getJSON 方法来执行此操作,我如何获取 json 的原始字符串?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
将
dataType
设置为text
可防止 jQuery 将请求作为 JSONP 处理。 jQuery 在后台为这些类型的请求做了一些魔法(用 URL 中的callback=?
替换函数名称,并将success
函数定义为全局函数)。为什么您希望响应是原始文本?不可能从 JSONP 请求中获取只是 JSON 的响应,因为 JSONP 的性质要求将响应包装在函数调用中。
将
dataType
设置为jsonp
可以,但当然会返回一个对象。如果你想要一个字符串,你可以在服务器上对部分响应进行双重 json 编码,以便将其作为字符串接收,或者在客户端上使用 JavaScript JSON 编码器并再次对其进行编码,但两者都不会看起来确实是理想的解决方案。对象更加可用和有用。
Setting the
dataType
totext
prevents jQuery handling the request as a JSONP. jQuery does some magic in the background for these type of requests (substitutingcallback=?
in the URL for a function name, and defining thesuccess
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
tojsonp
works, but of course an object is returned.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.