0

我的页面上有一组按钮,一些我想进行某个 Ajax 调用,而其他按钮则进行不同的 Ajax 调用,我应该使用数据类型并在其上放置一个 if 语句。

$("button").click(function () {
    //SOME BUTTONS AJAX THIS CALL
    //This Ajax toggles device on and off
    var $x10Device = $(this).parent().attr("class");
     $.ajax({
        type: 'GET',
        url: "http://192.168.0.34:81/tenHsServer/tenHsServer.aspx",
        data: {
            t: "ab",
            f: "ToggleDevice",
            d: $x10Device
        },
        error: function (request, status, error) {
            alert(request.responseText);
        }
    });
    //OTHER BUTTONS THIS AJAX CALL
    //This Ajax checks the current on/off status of the passed X10 code
    $.ajax({
        url: "urlencode.php",
        data: data,
        type: "POST",
        success: function (data) {
            myd = $('<span />').html(data).find("#Result").text();
            console.log(myd);
            if (myd == 'C5:2;') {
                $('img').attr('src', 'lightbulbon.png')
            } else {
                $('img').attr('src', 'lightbulboff.png')
            };
        },
        error: function (request, status, error) {
            alert(request.responseText);
        }
    });

});
4

3 回答 3

4

将语义 css 类添加到您的按钮标记中。将不同的 AJAX 请求放在相应的单击事件处理程序中。

$("button.toggleStatus").click(function() {
  // ajax request for toggling
});

$("button.checkStatus").click(function() {
  // ajax request for updating status
});
于 2013-06-26T19:54:45.093 回答
0

尝试为每个按钮添加一个类(就像 Thomas 提到的那样)。您还可以遍历按钮检查它们的类名,并在找到匹配项时调用 ajax 函数。也许是这样的:

var btn = $("button");
$.each(btn, function (index) {
    var ctx = $(this);
    if (ctx.hasClass("firstButton")) {
        // call appropriate ajax function here
    }
    if (ctx.hasClass("secondButton")) {
        // call appropriate ajax function here
    }
});
于 2013-06-26T20:10:12.447 回答
-1

使用按钮的 id 并将每个 ajax 请求放在各自的点击事件中......

$("button#button1").click(function() {
 // ajax request for button 1
});

$("button#button2").click(function() {
 // ajax request for button 2
});
于 2013-06-26T19:48:32.393 回答