我正在尝试构建一个简单的检查,它将接受一个字符串并检查该字符串是否存在 Twitter 帐户。
我已成功获得阳性结果,但似乎无法获得阴性结果。 $.ajax()
有一个错误元素,但它没有触发。
代码:
var testTwit = function(username){
$.ajax({
url: 'http://twitter.com/statuses/user_timeline.json?screen_name='+username+'&count=1&callback=?',
dataType: 'json',
success: function(){
alert("username is valid");
},
error: function(){
alert("username is valid");
}
})
}
最佳答案
您正在使用 JSONP 传输。在此传输中,请求的 URL 只是添加为 <script>
文档中的标签。如果 URL 返回非 200 状态代码,浏览器将不会执行它:这就是您看不到否定响应的原因。
一种解决方案是使用 suppress_response_codes
参数,以便 API 始终返回 200 状态代码。
参见Things Every Twitter Developer Should Know :
suppress_response_codes
: If this parameter is present, all responses will be returned with a 200 OK status code - even errors. This parameter exists to accommodate Flash and JavaScript applications running in browsers that intercept all non-200 responses. If used, it’s then the job of the client to determine error states by parsing the response body. Use with caution, as those error messages may change.
顺便说一句,Twitter 正在禁止对 API 进行未经身份验证的访问,因此 JSONP 访问也可能会被禁止。
关于javascript - 使用 AJAX/JSON 验证 Twitter 帐户是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12261184/