问题描述
我正在尝试使用http://goo.gl
API和以下jQuery函数来缩短URL
I'm trying to shorten a URL using the http://goo.gl
API with the following jQuery function
$.ajax({
url: 'https://www.googleapis.com/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));
}
});
我在JSON中收到以下错误:
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?
推荐答案
您无法在JavaScript中进行跨域POST.当您提到crossDomain为true且dataType为jsonp时,jQuery实际执行的操作是jsonp请求,这只是使用标记从另一台服务器获取数据的黑客.您会收到该错误,因为就好像您刚刚在API页面上进行了无参数的GET查询一样.另一台服务器需要意识到这一点,并需要对其进行支持.
You 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.
Goo.gl API页面完全没有提到jsonp,这使我相信它不支持它.最好的选择是用PHP编写一个代理为您执行命令并返回结果,然后对该PHP文件进行Ajax调用.
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.
如果是Chrome扩展程序,则可以使用特殊的Chrome方法进行跨域Ajax调用,以获取要传递给Ajax对象的URL.您还需要将远程URL添加到扩展清单文件中,如此处所述.
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.
这篇关于jQuery和Google URL Shortener API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!