开发者

onclick="func(); return false;" doesn't work when using $.get()

Consider a part of a web page:

<script>
function fun() {
    alert("Link won't work");开发者_运维技巧
}
</script>
<a href="http://google.com" onclick="fun(); return false;">link</a>

This works as is desired. But adding jquery $.get() command makes it fail:

<script>
function fun() {
    $.get("http://yahoo.com");
}
</script>
<a href="http://google.com" onclick="fun(); return false;">link</a>

Why is so? In general, in js I want to process href of <a /> element and use $.get() function to grab some data and then display it using other jquery functions. I still want <a /> to have href attribute.

Here in the example two external addresses are used but in my case I want to send requests within the same domain. By "failing" I mean that link will get me to the href address.


$.get() is used to send an AJAX request. Due to the same origin policy you cannot send an AJAX request to a different domain. So unless your site is hosted on yahoo.com, $.get("http://yahoo.com"); will always fail. Also if you was using jquery your code would probably more look like:

<script type="text/javscript">
$(function() {
    $('#link').click(function() {
        $.get('/somepage_on_your_server', function(result) {
            // Handle the result of the AJAX call
        });
        return false;
    });
});
</script>
<a href="http://google.com" id="link">link</a>


Given your problem description, I suspect you have a javascript error that is causing the code to not be executed at all. @Darin's should solve your problem unless the javascript error is elsewhere. In a situation like this I would use Firefox/Firebug and look at the console output to see if and where the error is.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜