jQuery URL bit.ly 缩短器
有人可以帮我使用这个 jQuery bit.ly URL 缩短器吗?
代码如下:
function shortenUrl(urlMatch)
{
var urlMatch = urlMatch
var username="myusername";
var key = 'R_897b82b73568ea74fffbafa5a7b846d';
$.ajax({
url:"http://api.bit.ly/v3/shorten",
data:{longUrl:urlMatch,apiKey:key,login:username},
dataType:"jsonp",
success:function(v)
{
var shortUrl=v.data.url;
return shortUrl;
}
});
}
$('button').click(function(){
var urlMatch = $(this).val();
var newUrl = shortenUrl(urlMatch);
$('#menu').html(newUrl);
});
每当我运行脚本时,它都会在控制台中返回以下代码:
jsonp1304728172115({ data : [ ] , "status_code" : 500, "status_txt": "missing_arg_uri"})
Will someone please help me with this jQuery bit.ly URL shortener?
The code is as follows:
function shortenUrl(urlMatch)
{
var urlMatch = urlMatch
var username="myusername";
var key = 'R_897b82b73568ea74fffbafa5a7b846d';
$.ajax({
url:"http://api.bit.ly/v3/shorten",
data:{longUrl:urlMatch,apiKey:key,login:username},
dataType:"jsonp",
success:function(v)
{
var shortUrl=v.data.url;
return shortUrl;
}
});
}
$('button').click(function(){
var urlMatch = $(this).val();
var newUrl = shortenUrl(urlMatch);
$('#menu').html(newUrl);
});
And whenever I run the script it returns this code in the console:
jsonp1304728172115({ data : [ ] , "status_code" : 500, "status_txt": "missing_arg_uri"})
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您有
data:{longUrl:urlMatch,apiKey:key,login:username},
如果 jsonp 类似于 json,那么您的数据参数格式不正确:
data:"{ 'longUrl':" + urlMatch + ",'apiKey':" + key + ",'login':" + username + "}",
上面的代码没有经过测试,但应该是类似的。
You have
data:{longUrl:urlMatch,apiKey:key,login:username},
If jsonp is anything like json, then you're data argument is not formed correctly:
data:"{'longUrl':" + urlMatch + ",'apiKey':" + key + ",'login':" + username + "}",
The above code is not tested, but it should be similar.
这样:
urlMatch = $(this).val();
会将按钮文本放入 urlMatch,这是您想要的吗?此外,回调上的
return
将不会到达该函数,因为ajax()
是一个异步函数。要使其同步,请将async:false
添加到ajax()
参数。并且
return
也不起作用,因此您必须将结果分配给全局变量。但最好的方法是将
return ShortUrl;
替换为$('#menu').html(shortUrl);
,因为这就是您正在寻找的结果。而且您不需要async:false
来执行此操作,这会阻止您的代码并暂时锁定浏览器。如果全部失败,请尝试在查询字符串本身上传递参数。您可能想要
This:
urlMatch = $(this).val();
will get the button text into urlMatch, is this what you want?Also, the
return
on the callback will not reach the function, becauseajax()
is an asynchronous function. To make it synchronous, addasync:false
toajax()
parameters.And
return
will not work as well, so you have to assign the result to a global var.But the best would be replacing
return shortUrl;
with$('#menu').html(shortUrl);
, since that's the outcome that you are looking for. And you don't needasync:false
for that, which will block your code and temporarily lock the browser.If all fails, try passing the parameters on the query string itself. You may want to take a look at this.
您在“var urlMatch = urlMatch”之后缺少分号
You're missing a semicolon after "var urlMatch = urlMatch"