点击后发布ajax变量

时间:2012-01-24 15:37:54

标签: jquery

我有一个锚链接如下:

<a class="show-next-page" id="10" href="#" name="category" rel="100000">

这是点击处理程序:

$('.show-next-page').click(function(){
    var prodId = $(this).attr("id");
    var catId = $(this).attr("rel");
    var type = $(this).attr("name");

    $.ajax({
        url: 'admin-catalog/next',
        type: 'POST',
        dataType: 'json',
        data: "catId=" + catId + "&prodId=" + prodId,
        success: ajaxCatProds
    });

    return false;
});

正如您所看到的,我将大量数据附加到此锚链接,但我开始用尽“有效”属性来附加更多数据。我现在开始认为这可能不是这样做的正确方法。

有人可以建议另类/更优雅的方法吗?

4 个答案:

答案 0 :(得分:2)

使用数据属性尝试此操作。

HTML

<a class="show-next-page" data-id="10" href="#" data-name="category" data-rel="100000">

JS

//This method will give all the data attributes associated with the element.
var dataAttrib = $(this).data();
var data = {
    //You access the data attribute with there name without data part
    prodId: dataAttrib.id,
    catId: dataAttrib.rel,
    type: dataAttrib.name
};

$.ajax({
        url: 'admin-catalog/next',
        type: 'POST',
        dataType: 'json',
        data: data,
        success: ajaxCatProds
});

答案 1 :(得分:1)

我建议查看jQuery的.data() methoddocs中所述的说明:

  

存储与指定关联的任意数据   元件。返回已设置的值。

示例设置:

$.data("[YourElementID]", 'categoryID', 52);

示例获取:

var catID = $.data("[YourElementSelector]", 'categoryID');

答案 2 :(得分:1)

您可以使用data-命名约定来使用自定义属性。 (例如data-amountdata-dataTypeID等。)

jQuery的.data()函数也知道这些命名属性,并且可以在没有data-前缀的情况下访问它们。

答案 3 :(得分:-1)

$('.show-next-page').click(function(){
    var prodId = $(this).attr("id");
    var catId = $(this).attr("rel");
    var type = $(this).attr("name");

    $.ajax({
        url: 'admin-catalog/next',
        type: 'POST',
        dataType: 'json',
        data: {'catId':catId ,'prodId':prodId,'type': type},
    });

    return false;
});