javascript - 如何在ajax中获取href的参数

标签 javascript html ajax

我正在尝试在 ajax 中获取 href 的参数。

<a href="index.php?del_id=<?php echo $c_id; ?>" class="delete" value="<?php echo $c_id ?>">Delete</a></li>

现在我正尝试在 ajax 中获取 del_id

<script type="text/javascript">
    $(".delete").click(function(){
        var url = ($(this).attr('href'));
        var id=    getURLParameter(url,'del_id');
        if(confirm('Are you sure to remove this file ?'))
        {
            $.ajax({
               url: 'maincode.php',
               type: 'GET',
               data: {id: id},
               success: function(data) 
                {
                    alert("file removed successfully");  
                },
                error:function()
                {
                 alert('Something is wrong');
                }
            });
        }
    });
</script>

但是在添加 getURLParameter 代码后,代码没有得到进一步执行。请帮助我。

最佳答案

你真的不需要考虑太多,参数已经在 url 中了:

---- href="index.php?del_id=<?php echo $c_id; ?>"

$(".delete").click(function(){
    var url = ($(this).attr('href')); // this already has the id in it 
    if(confirm('Are you sure to remove this file ?'))
    {
        $.ajax({
           url: 'maincode.php',
           type: 'GET',
           // remove this, the data is in the url -- data: {id: id}, 
           success: function(data) 
            {
                alert("file removed successfully");  
            },
            error:function()
            {
             alert('Something is wrong');
            }
        });
    }
});

在服务器上,会有一个get参数叫del_id 如果您需要参数为id,请将url更改为:

index.php?id=<?php echo $c_id; ?>

如果你真的想用代码填充数据,使用数据参数

<a href="#" data-del-id="<?php echo $c_id; ?>" data-url="index.php" >

// JAVASCRIPT SIDE: 
var url = $(this).data('url'); // OR : $(this).attr('data-url');
var id  = $(this).data('del-id'); // OR : $(this).attr('data-del-id');

我希望这是有道理的

关于javascript - 如何在ajax中获取href的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51249520/

相关文章:

javascript - Socket.io - 无法连接到客户端

javascript - 如何让 <select> 框从包含的 <div> 中溢出?

javascript - 一旦找到就中断 for 循环并返回结果

javascript - bootstrap static 固定导航栏在滚动条上跳跃

html - 为什么这些 div 之间有垂直空间?

html - 在 TiddlyWiki 5 中,如何防止代码块内的文本换行?

c# - 部分 View 不会在 ajax.beginform 之后更新

javascript - asp.net mvc vs javascript 构建整个站点

javascript - Highcharts : plot line and plot click event

ajax - 页面和Ajax调用Spring异常处理