0

Hello to those viewing this!

I'm having some trouble a bad Ajax call. In my MVC3 project I have a database that registers a row when a user adds another user on his friend list.

Here is the html/Razor code:

@if(!Model.areFriends){
    <div id="AddFriendAncor" class="AddButton"><a href="#" id="@Model.theUser.userID" class="Add">Add to friendlist</a></div>
}
else
{
    <div class ="AddFriendAncor"><a href="#" id="DoneAdding">You are friends</a></div>   
}

Here is the Javascript/jQuery/Ajax code.

$(".Add").on("click", function (event) {
    event.preventDefault();
    var acceptThisFriend = { "ID": event.target.id };
    $.ajax({
        type: "POST",
        url: "/Profile/AddFriend",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: JSON.stringify(acceptThisFriend),
        success: function () { alert("Works");},
        error: function ()
        {
            document.getElementById(acceptThisFriend.ID).innerHTML = "Friend Added";
        }
    });
});

You might notice that the error function actually holds what the success function should have. The reason is that it works that way. It's terrible, but I had to get something working.

Also, it adds two instances to the database. This is because it dynamically creates the Html, any ideas on how to unbind this when I create it?

EDIT: The AddFriend function:

The AddFriend function was made into this instead:

    public virtual ActionResult AddFriend(string ID)
    {
        System.Diagnostics.Debug.WriteLine(ID);
        var friendID = Convert.ToInt32(ID);
        var user = u_rep.GetUser(User.Identity.Name);

        f_rep.AddFriend(user.userID, friendID);
        return Json(true);
    }

I changed the AddFriend to look like what it does above, now the Ajax gets something and returns success, but I still add twice to the database dispite changing my Ajax to this:

$(".Add").on("click", function (event) {
    event.preventDefault();
    var acceptThisFriend = { "ID": event.target.id };
    $.ajax({
        type: "POST",
        url: "/Profile/AddFriend",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: JSON.stringify(acceptThisFriend),
        success: function () { $("#AddFriendAncor").replaceWith("<p>Vini bætt við</p>"); },
        error: function ()
        {
            alert("fail");
        }
    });
});
4

1 回答 1

0

将成功函数更改为如下所示:

success: function () { $("#AddFriendAncor").replaceWith("<p>Friend added</p>").unbind('click'); },

现在它只触发一次。修改后的 AddFriend 函数确保 Ajax 对其工作有一些响应。

于 2013-05-12T22:09:20.610 回答