0

如果我运行它,我会收到“正在发送”的消息,但不会显示“已收到”的消息。为什么?错误消息是失败和错误块中的无传输。

html:

<ul>
    <li><a href="http://www.hotmail.com">hotmail.com</a></li>
    <li><a href="http://www.google.com">google.com</a></li>
</ul>

js:

<script type="text/javascript">
    $(document).ready(function () {
        $("a").each(function (index) {
            var sUrl = 'http://tinyurl.com/api-create.php?url=' + $(this).attr('href')
            alert('sending: ' + sUrl);
            $.ajax({
                url: sUrl,
                crossDomain: true
            }).fail(function (data) {
                alert('failed: ' + data.statusText);
            }).error(function (data) {
                alert('error: ' + data.statusText);
            }).done(function (data) {
                alert('received: ' + sUrl);
            });
        });
    });
</script>

编辑:接受的答案使用 $.getJSON 在内部调用 $.ajax。对于那些可能对低级 $.ajax 感兴趣的人,请看这里。

$('a').each(function (index) {
    var app = 'http://json-tinyurl.appspot.com/';
    var sUrl = app + '?url=' + $(this).attr('href') + '&callback=?';
    $.ajax({
        url: sUrl,
        dataType: 'json',
        success: function (data) {
            alert('ajax:' + data.tinyurl);
        },
        error: function (jqXHR, textStatus, errorThrown) {
            alert("jqXHR=" + jqXHR.responseText + "\ntextStatus=" + textStatus + "\nerrorThrown=" + errorThrown);
        }
    });
});
4

2 回答 2

2

您遇到问题是因为您正在进行跨域调用而不是使用 jsonp。有关您的 tinyurl 生成问题的解决方案,请参见此处的答案:

通过 Jquery Ajax 调用创建 TinyURL

使用它作为参考,这是您的固定代码:

$(document).ready(function() {
    $("a").each(function(index) {
        var sUrl = $(this).attr('href');
        $.getJSON("http://json-tinyurl.appspot.com/?&callback=?", {
            url: sUrl
        }, function(data) {
            alert(data.tinyurl);
        });
    });
});​
于 2012-05-26T20:51:06.143 回答
2

crossDomain 参数并不像您认为的那样做。来自 JQuery 文档:

If you wish to force a crossDomain request (such as JSONP) on the same domain, set the value of crossDomain to true. This allows, for example, server-side redirection to another domain.

Note that if you're requesting a URL from a different domain over AJAX, JQuery will set this to true by default - so it is unnecessary for you to set it yourself.

The reason the code isn't working is you haven't set up cross domain AJAX properly. Due to potential security vulnerabilities, browsers follow the Same Origin Policy for AJAX requests. So the fact that you're trying to access the tinyURL API with an AJAX request will be blocked automatically by the browser. You will need to use a mechanism such as JSONP to get this to work.

Try this blog post, which has an example of using JQuery/AJAX/JSONP to get shortened URLs from the TinyURL API. It also has some background links about JSONP at the end. Note that it's a bit old, so you may need to update the syntax to the current JQuery/TinyURL API. The basic ideas behind working with JSONP are unchanged.

于 2012-05-26T20:52:43.643 回答