1

goo.gl API を使った短縮 URL を作ろうとしています。しかし、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。そこから抽出する方法は?

4

1 に答える 1

2

JSON.parse()を指定すると jQuery が自動的に呼び出すため、 を呼び出す必要はありませんdataType: 'json'。必要な値は のidプロパティになりますresponse

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);
    }
});
于 2013-11-14T20:40:00.403 に答える