【问题标题】:How to extract text from JSON response?如何从 JSON 响应中提取文本?
【发布时间】:2013-11-14 20:22:10
【问题描述】:

我正在尝试制作使用 goo.gl API 的网址缩短器。但是当我必须从 JSON 响应中获取短 URL 时,我卡住了!

在 Chrome 控制台中输入此代码后:

var longURL = "http://stackoverflow.com/questions/ask"
$.ajax({
                url: 'https://www.googleapis.com/urlshortener/v1/url?shortUrl=http://goo.gl/fbsS&key=AIzaSyANFw1rVq_vnIzT4vVOwIw3fF1qHXV7Mjw',
                type: 'POST',
                contentType: 'application/json; charset=utf-8',
                data: '{ longUrl: "' + longURL +'"}',
                dataType: 'json',
                success: function(response) {
                    var result = JSON.parse(response); 
                }
            });

我得到以下输出:

我看到我的短 URL 在 resoinseText.id。如何从那里提取它?

【问题讨论】:

  • 因为你指定了dataType: 'json',jQuery 会自动解析它。你不应该自己打电话给JSON.parse()
  • 另一方面,您应该在创建数据时使用JSON.stringify(),而不是尝试手动构造JSON。
  • @Barmar,那么,如何使用我的短 URL 获取变量?
  • @Barmar console.log(result); 打印 false
  • 您是在控制台还是在success 函数中执行此操作? response 变量是函数的本地变量。

标签: javascript jquery ajax json google-api


【解决方案1】:

您不需要调用JSON.parse(),因为当您指定dataType: 'json' 时,jQuery 会自动执行此操作。然后,您想要的值将位于 responseid 属性中。

var longURL = "http://stackoverflow.com/questions/ask"
$.ajax({
    url: 'https://www.googleapis.com/urlshortener/v1/url?shortUrl=http://goo.gl/fbsS&key=AIzaSyANFw1rVq_vnIzT4vVOwIw3fF1qHXV7Mjw',
    type: 'POST',
    contentType: 'application/json; charset=utf-8',
    data: '{ longUrl: "' + longURL +'"}',
    dataType: 'json',
    success: function(response) {
        console.log(response.id);
    }
});

【讨论】:

  • 你在这里:) link
猜你喜欢
  • 2023-03-13
  • 1970-01-01
  • 1970-01-01
  • 2012-04-16
  • 1970-01-01
  • 1970-01-01
  • 2019-04-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多