-1

新手问题请多多包涵。这是一个简单的 ajax 代码:单击按钮删除服务器上的图像。但是在 Firebug>Net>XHR 中,我看不到这个请求。

PS:我将删除按钮的类型设置为“按钮”而不是“提交”以防止页面刷新,这是正确的做法吗?

$('.delete').on('click', function() {
    var currentpath = window.location.pathname;
    var path = currentpath + '/delete';
    var csrftoken = $.cookie('csrftoken');
    var data = {};
    data['csrfmiddlewaretoken'] = csrftoken;
    data ['filename'] = $('.image-input').val();

    $.ajax({
        url: path,
        type: 'POST',
        data: data,
        cache: false,
        contentType: false,
        processData: false,
        success: function(data){
            $('button.delete').css('visibility', 'hidden');
        }
    });
});


编辑:删除按钮的代码

<button type='button' class='delete first'>&#x274C</button>


EDIT2:代码的意图

我需要的只是将文件名字符串传递给服务器,以便服务器可以通过该字符串查询图像并删除该图像。而且我不希望页面刷新。

4

4 回答 4

2

访问您的按钮类单击如下:

$(document).on("click", ".delete", function(){
    // YOUR CODE STUFF
});

有关详细信息,请查看.on()

于 2013-05-28T09:40:28.400 回答
1
$(function(){
$('.delete').on('click', function() {
    //var currentpath = window.location.pathname;
    var path = 'delete';
    var csrftoken = $.cookie('csrftoken');
    var data = {};
    data['csrfmiddlewaretoken'] = csrftoken;
    data ['filename'] = $('.image-input').val();

    $.ajax({
        url: path,
        type: 'POST',
        data: data,
        cache: false,
        //contentType: false,
        //processData: false,
        success: function(data){
            alert('success');
            $('.delete').css('visibility', 'hidden');
        }
    });
});
});
于 2013-05-28T09:44:24.577 回答
0

Try this:

$('.delete').on('click', function(e) {

    e.preventDefault();
    var currentpath = window.location.pathname;
    var path = currentpath + '/delete';
    var csrftoken = $.cookie('csrftoken');
    var filename = $('.image-input').val();
    var data = JSON.stringify({ csrfmiddlewaretoken: csrftoken, filename: filename }),

    $.ajax({
        url: path,
        type: 'POST',
        data: data,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        cache: false,
        success: function(data){
            $('button.delete').css('visibility', 'hidden');
        }
    });
});
于 2013-05-28T09:43:47.193 回答
0

定义错误回调函数也很好。为什么不使用谷歌浏览器的检查元素和一些断点进行调试?

$(".delete").click(function(){
    var currentpath = window.location.protocol+"//"+window.location.host;
    var path = currentpath + '/delete';
    var csrftoken = $.cookie('csrftoken');
    var data = new Object();
    data['csrfmiddlewaretoken'] = csrftoken;
    data ['filename'] = $('.image-input').val();

    $.ajax({
        url: path,
        type: 'POST',
        data: data,
        cache: false,
        dataType: 'json',
        contentType: false,
        processData: false,
        success: function(data){
            $('button.delete').css('visibility', 'hidden');
        }
    });
});
于 2013-05-28T09:45:35.813 回答