开发者

Doing a DELETE request from <a> tag without constructing forms?

Is there any way to force an <a href> to do a delete request when clicked instead of a regular GET?

The "Rails" way is to dynamically generate a <form> tag that adds the appropriate params so that it gets routed to the right place, however I'm not too fond of that much DOM manipulation for such a simple task.

I thought about going the route of something like:

$("a.delete").click(funct开发者_JS百科ion(){
    var do_refresh = false;
    $.ajax({
        type: "DELETE",
         url: "my/path/to/delete",
     success: function(){
                  do_refresh = true;
              },
     failure: function(){
                  alert("There is an error");
              }
    });
    return do_refresh; //If this is false, no refresh would happen. If it
                      //is true, it will do a page refresh.
});

I'm not sure if the above AJAX stuff will work, as it's just theoretical. Is there any way to go about this?

Note:

Please don't recommend that I use the rails :method => :delete on link_to, as I'm trying to get away from using the rails helpers in many senses as they pollute your DOM with obtrusive javascript. I'd like this solution to be put in an external JS file and be included as needed.


According to the docs:

http://api.jquery.com/jQuery.ajax/

the DELETE method is allowed but not supported on all browsers, so you should take a look here:

Are the PUT, DELETE, HEAD, etc methods available in most web browsers?


This is what i do:

$("a.delete").live('click', function() {
        $.post(this.href, "_method=delete", function(data) {
            //do refresh
        });
        return false;
    })

But i don't really know which all browsers support it and which don't. I tested it on mac with Firefox 2 and 3.6, safari 3 and chrome beta 5.0.375.70 and it works.


You can use RESTInTag plugin, it will do the ajax requests for you all you have to do is add a couple of extra attributes to your HTML tag

Example:

HTML

<button class="delete" data-target="my/path/to/delete" data-method="DELETE" data-disabled="true">Delete Article</button>

JavaScript

$(".delete").restintag(optionsObj, function() {
    do_refresh = true
},
function() {
    alert("some error happened");
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜