程序go 2012-11-08 15:21 采纳率: 100%
浏览 291

在超链接中使用ajax

I've created a bookmark page that retrieves links from a database and displays it. I'm able to log in, add new links & delete them. However, when I delete an entry it displays delete.php instead of loading the page onto itself (the query does work).

I've most likely over-complicated my code at this point and am probably overlooking something simple, as I've used a lot of JavaScript for other elements of the page.

The entries are added dynamically so this part of the HTML is being appended:

<h2>
    <a href="delete.php?URL='+url+'">[x]</a>
</h2>
<a href="'+url+'" target="iFrame" class="linkURL">
    <div class="bookmark">
        <h3 style="float: left;">'+title+'</h3>
        <br />
        <p>'+desc+'</p>
    </div>
</a>

JavaScript:

//  DELETE FUNCTION
$("h2 a").click(function() {
    return false;
    var action = $(this).attr('href');
    var form_data = {
        URL: $("#linkURL").attr('href'),
        is_ajax: 1
    }; // form_data
    $.ajax({
        type: "POST",
        url: action,
        data: form_data,
        success: function(response){
            if(response == 'success') {
                alert('Successful delete!');
            } else { // if
                alert('Delete failed.');
            } // else
        } // function(response)
    }); // ajax
    return false;
}); // h2

The page is located here: http://samaradionne.com/links6/ if it is easier to view the whole thing.

  • 写回答

2条回答 默认 最新

  • weixin_33709219 2012-11-08 15:28
    关注

    You are using both an anchor tag a and a click event. You are getting the actual delete.php page because when you click on the anchor tag it works just like any regular link. You have no where in your code something that says "hey, don't actually follow this link like normal".

    To not follow the link, you need

    <a href="yoururl" onclick="return false;">[x]</a>
    

    Furthermore, you attached your jQuery click event to the h2, which is not bad in of itself, just confusing as the intent is to actually click the link. In that case, you need:

    $("h2 a").click(function(){});
    

    Lastly, to bring this all together, you could do the following:

     $("h2 a").click(function(){
         // your normal logic
    
         return false; // don't follow link
     });
    

    And then you don't have to have the onclick inside the anchor tag.

    评论

报告相同问题?

悬赏问题

  • ¥15 数学的三元一次方程求解
  • ¥20 iqoo11 如何下载安装工程模式
  • ¥15 本题的答案是不是有问题
  • ¥15 关于#r语言#的问题:(svydesign)为什么在一个大的数据集中抽取了一个小数据集
  • ¥15 C++使用Gunplot
  • ¥15 这个电路是如何实现路灯控制器的,原理是什么,怎么求解灯亮起后熄灭的时间如图?
  • ¥15 matlab数字图像处理频率域滤波
  • ¥15 在abaqus做了二维正交切削模型,给刀具添加了超声振动条件后输出切削力为什么比普通切削增大这么多
  • ¥15 ELGamal和paillier计算效率谁快?
  • ¥15 蓝桥杯单片机第十三届第一场,整点继电器吸合,5s后断开出现了问题