admin管理员组文章数量:1289829
I'm trying to shorten a URL using the API with the following jQuery function
$.ajax({
url: '',
crossDomain: true,
type: 'POST',
contentType: 'application/json',
data: '{longUrl:"'+encodeURI(url)+'"}',
dataType: 'jsonp',
success: function(e) {
alert(JSON.stringify(e));
}
});
And I get the following Error in JSON :
{"error":{"errors":[{"domain":"global","reason":"required","message":"Required parameter: shortUrl","locationType":"parameter","location":"shortUrl"}],"code":400,"message":"Required parameter: shortUrl"}}
Why does it ask for a Short URL? What am I doing wrong?
I'm trying to shorten a URL using the http://goo.gl
API with the following jQuery function
$.ajax({
url: 'https://www.googleapis./urlshortener/v1/url?key=MY_API_KEY',
crossDomain: true,
type: 'POST',
contentType: 'application/json',
data: '{longUrl:"'+encodeURI(url)+'"}',
dataType: 'jsonp',
success: function(e) {
alert(JSON.stringify(e));
}
});
And I get the following Error in JSON :
{"error":{"errors":[{"domain":"global","reason":"required","message":"Required parameter: shortUrl","locationType":"parameter","location":"shortUrl"}],"code":400,"message":"Required parameter: shortUrl"}}
Why does it ask for a Short URL? What am I doing wrong?
Share Improve this question edited Feb 9, 2016 at 17:22 Kara 6,22616 gold badges53 silver badges58 bronze badges asked Jul 15, 2011 at 14:12 smoizssmoizs 3394 silver badges15 bronze badges 1- Try with JSONP or do it server-side. – Marko Commented Sep 11, 2012 at 5:31
2 Answers
Reset to default 6You can't do a cross-domain POST in JavaScript. What jQuery actually does when you mention crossDomain to be true and the dataType to be jsonp is a jsonp request, which is just a hack to get data from another server using a tag. You get that error because it's as if you had just done a GET requets on the API page with no parameters. The other server needs to be aware of this and needs to support it.
The Goo.gl API page has no mention of jsonp at all which makes me believe it doesn't support it. Your best bet would be to write a proxy in PHP to do the requets for you and return the result, and then do an Ajax call on that PHP file.
Edit: If it's a Chrome extension, you can do a cross-domain Ajax call using a special Chrome method to get the URL to pass to the Ajax object. You also need to add the remote URL to your extension manifest file, as documented here.
Here's a working code.
$.ajax({
url: 'https://www.googleapis./urlshortener/v1/url?key={API-KEY}',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: '{ longUrl: "' + longURL +'"}',
success: function(response) {
$('#inputBox').val(response.id);
}
});
本文标签: javascriptjQuery and Google URL Shortener APIStack Overflow
版权声明:本文标题:javascript - jQuery and Google URL Shortener API - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741441323a2378935.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论