如何使 Javascript AJAX 函数(带 JQuery)与 onclick 一起使用?

发布于 2024-10-12 01:46:53 字数 595 浏览 0 评论 0原文

我想知道最好的方法是什么,创建一个通用的 javascript 函数来发出 AJAX 请求并使用“onclick”调用它,请记住,我需要加载的 ajax 结果才能仍然使用此函数。另外,我正在使用 JQuery 和 PHP。大致如下:

<a href="#" onclick="postLike(<?php echo $post_id; ?>);">Like Post</a>

<script>
function postLike(post_id){
    $.ajax({
        async:true,
        dataType:"html",
        position:"html",
        success:function (data, textStatus) {
            $("#post-"+post_id+"-like").html(data);
        },
        url: "domain\/likes\/like\/"+post_id
    });
    return false;
}
</script>

不过似乎对我不起作用。

谢谢!

I was wondering what the best way was the handle creating a generic javascript function that makes an AJAX request and calling it with 'onclick', keeping in mind I need the loaded ajax results to still work with this function. Also, I'm using JQuery and PHP. Something along the lines of:

<a href="#" onclick="postLike(<?php echo $post_id; ?>);">Like Post</a>

<script>
function postLike(post_id){
    $.ajax({
        async:true,
        dataType:"html",
        position:"html",
        success:function (data, textStatus) {
            $("#post-"+post_id+"-like").html(data);
        },
        url: "domain\/likes\/like\/"+post_id
    });
    return false;
}
</script>

Doesn't seem to work for me though.

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

可爱暴击 2024-10-19 01:46:53

我不确定你的问题是什么,但这就是我处理它的方式。请注意,这可以避免帖子 ID 为字母数字时出现的问题,因为它将其附加到 href 并从那里提取。请注意,它一开始是隐藏的,并且仅在启用 JavaScript 时才显示(无论如何,这是使其工作所必需的)。

要找到您的问题,您应该考虑添加错误处理程序并使用 Firefox/Firebug 查看发出的请求(和响应)。

<a class="like" href="#<?php echo $post_id; ?>");" style="display: none'">Like Post</a>

<script type="text/javascript"> 
    $(function() {
        $('.like').show().click( function() {
            var post_id = $(this).attr('href').replace(/^#/,'');
            $.ajax({
                async:true,
                dataType:"html",
                success:function (data, textStatus) {
                     $("#post-"+post_id+"-like").html(data);
                },
                url: "domain/likes/like/"+post_id
            });
            return false;
     }
</script>

支持支持 javascript/非 javascript 的浏览器的替代方案

注意:您的后端代码需要能够区分 AJAX 和非 AJAX 请求。请注意,您可以使用 X_REQUESTED_WITH 标头 (HTTP_X_REQUESTED_WITH) 来执行此操作进行 AJAX 调用时由 jQuery 添加。欺骗是有可能的,所以要小心如何使用此检查——比如不要将任何身份验证或授权决策基于它。当您收到 AJAX 请求时,只需返回 HTML 片段即可。对于非 AJAX,您需要再次渲染整个页面。

<a class="like" href="/domain/likes/like/<?php echo $post_id; ?>");">Like Post</a>

<script type="text/javascript"> 
    $(function() {
        $('.like').show().click( function() {
            var url = $(this).attr('href');
            $.ajax({
                async:true,
                type: 'post', // technically it changes data so post is RESTful
                dataType:"html",
                success:function (data, textStatus) {
                     $("#post-"+post_id+"-like").html(data);
                },
                url: url
            });
            // cancel the default link action so we don't get two like's
            return false;
     }
</script>

I'm not sure what your problem is, but this is how I would handle it. Note that this avoids the issue when the post id is alphanumeric since it appends it to the href and extracts it from there. Note that the it starts hidden and is displayed only if javascript is enabled (which is required to make it work anyway).

To find your problem you should consider adding an error handler and using Firefox/Firebug to view the requests (and responses) as they are made.

<a class="like" href="#<?php echo $post_id; ?>");" style="display: none'">Like Post</a>

<script type="text/javascript"> 
    $(function() {
        $('.like').show().click( function() {
            var post_id = $(this).attr('href').replace(/^#/,'');
            $.ajax({
                async:true,
                dataType:"html",
                success:function (data, textStatus) {
                     $("#post-"+post_id+"-like").html(data);
                },
                url: "domain/likes/like/"+post_id
            });
            return false;
     }
</script>

An alternative to support both javascript/non-javascript enabled browsers

Note: your backend code needs to be able to distinguish between AJAX and non-AJAX requests. Note you can do this using the X_REQUESTED_WITH header (HTTP_X_REQUESTED_WITH) added by jQuery when making AJAX calls. It is possible to spoof so be careful how you use this check -- like not basing any authentication or authorization decisions on it. When you get an AJAX request, just return the HTML snippet. For non-AJAX you'll need to render the entire page again.

<a class="like" href="/domain/likes/like/<?php echo $post_id; ?>");">Like Post</a>

<script type="text/javascript"> 
    $(function() {
        $('.like').show().click( function() {
            var url = $(this).attr('href');
            $.ajax({
                async:true,
                type: 'post', // technically it changes data so post is RESTful
                dataType:"html",
                success:function (data, textStatus) {
                     $("#post-"+post_id+"-like").html(data);
                },
                url: url
            });
            // cancel the default link action so we don't get two like's
            return false;
     }
</script>
三生路 2024-10-19 01:46:53

最好的方法是通过 jQuery .bind、.live 或 .delegate 函数将函数绑定到 onclick(或 jQuery 中的 .click)事件。

The best way is binding functions to onclick (or .click in jQuery) event by jQuery .bind, .live or .delegate functions.

蓝颜夕 2024-10-19 01:46:53

首先,如果你使用jQuery,则不需要使用锚标记的onclick属性(感觉很唐突)。尝试这个语法:

<a href="#" id="postLike" <other attributes>>Like Post</a>

<script type="text/javascript">
$('#posLike').click(function(){
    $.ajax({
        async:true,
        dataType:"html",
        position:"html",
        success:function (data, textStatus) {
            $("#post-"+post_id+"-like").html(data);
        },
        url: "domain\/likes\/like\/"+post_id
    });
    return false;
});
</script>

First of all if you are using jQuery, you don't need to use onclick attribute of anchor tag(it feels very obtrusive). try this syntax:

<a href="#" id="postLike" <other attributes>>Like Post</a>

<script type="text/javascript">
$('#posLike').click(function(){
    $.ajax({
        async:true,
        dataType:"html",
        position:"html",
        success:function (data, textStatus) {
            $("#post-"+post_id+"-like").html(data);
        },
        url: "domain\/likes\/like\/"+post_id
    });
    return false;
});
</script>
雨巷深深 2024-10-19 01:46:53

以下是我通常解决此问题的方法:

在 PHP 中,当您需要循环出帖子并生成链接时,为锚点分配唯一的 id,如下所示:

foreach ($posts as $post) {
    echo "<a href='javascript://' class='like-anchors' id='like-post-{$post['id']}'>Like Post</a>";
}

然后在 JS 代码中,您可以执行以下操作:

$(document).ready(function() {
    $('.like-anchors').click(function() {
        var id = $(this).attr('id').substring(10);
        $.get("domain/likes/like/"+id, function(data) {
             $('#post-'+id+'-like').html(data);
        });
    });
});

< strong>注意

  1. 您没有使用 post 或任何高级 Ajax 功能。 $.get 应该足够了。请随意对此发表评论。
  2. 使用 href="javascript://" 因为我不希望浏览器滚动到顶部
  3. 更好的是,您可以为包装器 div 分配一个全局 id,这样您就不会耗尽您的资源id。说如果我有帖子、内容和喜欢按钮,我会这样做:

PHP

<?php foreach($posts as $post): ?>
<div class="post-body" id="post-<?php echo $post['id'] ?>">
    <div class="post-content"></div>
    <div class="post-controls">
        <a href="javascript://" class="post-like">Like This Post</a>
    </div>
</div>
<?php endforeach; ?>

JS

$(document).ready(function() {
    $('.post-like').click(function() {
        var parent = $(this).parent().parent();
        var id = parent.attr('id').substring(5);
        $.get("domain/likes/like/"+id, function(data) {
             parent.children('.post-content').html(data);
        });
    });
});

有很多方法可以完成任务。这些只是我的 2 美分

干杯

Here is what I normally do to fix this problem:

In your PHP, when you need to loop out the posts and generate the links, assign unique ids for the anchors, like this:

foreach ($posts as $post) {
    echo "<a href='javascript://' class='like-anchors' id='like-post-{$post['id']}'>Like Post</a>";
}

Then in your JS code, you can do this:

$(document).ready(function() {
    $('.like-anchors').click(function() {
        var id = $(this).attr('id').substring(10);
        $.get("domain/likes/like/"+id, function(data) {
             $('#post-'+id+'-like').html(data);
        });
    });
});

Note

  1. You are not making use of post or any advance Ajax functions. $.get should be enough. Feel free to comment on this.
  2. Using href="javascript://" because I don't want the browser to scroll to top
  3. Even better, you can just assign a global id to the wrapper div, so you won't exhaust your ids. Says if I have post, content, and like button, I would do this:

PHP

<?php foreach($posts as $post): ?>
<div class="post-body" id="post-<?php echo $post['id'] ?>">
    <div class="post-content"></div>
    <div class="post-controls">
        <a href="javascript://" class="post-like">Like This Post</a>
    </div>
</div>
<?php endforeach; ?>

JS

$(document).ready(function() {
    $('.post-like').click(function() {
        var parent = $(this).parent().parent();
        var id = parent.attr('id').substring(5);
        $.get("domain/likes/like/"+id, function(data) {
             parent.children('.post-content').html(data);
        });
    });
});

There are many ways to complete the task. These are just my 2 cents

Cheers

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文