简体   繁体   English

成功回调中的JQuery Ajax Type错误

[英]JQuery Ajax Type error in success callback

I create a button that when clickes do something with Ajax in server and when come back from server color of the button and its text will change (something like +1 add friend in facebook) here is my code in .js : 我创建了一个按钮,当点击服务器中的Ajax执行某些操作时,从按钮的服务器颜色返回并且其文本将更改(类似于在facebook中添加朋友的+1)这里是我在.js代码:

$(".blue").on("click", function(){
    var firstName = $(this).prev().prev().text();
    var lastName = $(this).prev().text();
    $(this).text("Add Friend...");
    var data={
        firstName: firstName,
        lastName: lastName
    };
    $.ajax({
        url: '/ajax/friendRequest',
        data: data,
        dataType: 'json',
        success:function(){
            alert(123);
            $(this).removeClass("glass blue");
            $(this).addClass("greenStatic");
            $(this).text("Request sent");
        }
    });
});

every thing is OK and request will successfully change the database but when it comeback to the success callback I only see the alert(123); 每件事都没问题,请求会成功更改数据库,但当它回到成功回调时我只看到alert(123); on the browser and 3 below lines don't run and my chrome developer tools throw exception of typeError I search SO and change $ sign to jQuery but still I have same problem 在浏览器和3下面的行不运行和我的chrome开发人员工具抛出typeError异常我搜索SO并将$ sign更改$ jQuery但我仍然有同样的问题

In your success callback $(this) doesn't refer to the button, cache it outside of the success callback, like 在你的成功回调$(this)中没有引用该按钮,将其缓存在成功回调之外,如

$(".blue").on("click", function(){
    var btn = $(this);
    ...
    ....
    success:function(){
        ...
        btn.addClass("greenStatic");
        ...
    }
});
        $(this).removeClass("glass blue");
        $(this).addClass("greenStatic");
        $(this).text("Request sent");

Here this does not refer to the control, rather it refers to the Ajax request object. 这里this并不是指控制,而它指的是Ajax请求的对象。 So, replace this by the control id. 所以,用控件ID替换this It should work. 它应该工作。

Something like below... 像下面的东西......

        $("#controlId").removeClass("glass blue");
        $("#controlId").addClass("greenStatic");
        $("#controlId").text("Request sent");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM