使用jquery ajax方法获取原始json字符串遇到问题

发布于 2024-09-06 17:07:55 字数 423 浏览 1 评论 0原文

我使用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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

笔芯 2024-09-13 17:07:55

dataType 设置为 text 可防止 jQuery 将请求作为 JSONP 处理。 jQuery 在后台为这些类型的请求做了一些魔法(用 URL 中的 callback=? 替换函数名称,并将 success 函数定义为全局函数)。

为什么您希望响应是原始文本?不可能从 JSONP 请求中获取只是 JSON 的响应,因为 JSONP 的性质要求将响应包装在函数调用中。

dataType 设置为 jsonp 可以,但当然会返回一个对象。

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

如果你想要一个字符串,你可以在服务器上对部分响应进行双重 json 编码,以便将其作为字符串接收,或者在客户端上使用 JavaScript JSON 编码器并再次对其进行编码,但两者都不会看起来确实是理想的解决方案。对象更加可用和有用。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文