【问题标题】:Consult ajax - show value cell table咨询ajax - 显示值单元格表
【发布时间】:2015-03-01 16:04:38
【问题描述】:

我想在我的表格数据中显示输入“名称”的值。

<table id="mytable">
    <tbody>
        <tr>
            <td><input id="id" class="id">1</input></td>
            <td><input id="name" class="name"></input></td>
        <tr>
    <tbody>
    <tbody>
        <tr>
            <td><input id="id" class="id">2</input></td>
            <td><input id="name" class="name"></input></td>
        <tr>
    <tbody>
</table>

我使用此代码获取值,但我不知道如何显示它。

$('#mytable tbody').each(function() {

    var id = $(this).find(".id").val(); //obtain Id value

    $.ajax({
        url:"search_name.php", //search in database name with this id
        type:"POST",
        data:id,
        dataType:"json",
        success:
            function(return)
            {
                $(this).find(".name").val(return.name); 
            }               
    })

});

})

return.name 的值没问题,我想显示但没有显示的名称 以类名出现在输入中。

【问题讨论】:

  • this在success函数里面是不是元素吗?
  • 并且 ID 在文档上下文中必须是唯一的...关于 ajax 成功回调上下文,用作 $.ajax() 选项:context: this, 请注意,return 是保留关键字,请使用其他关键字
  • return and Ids 没问题,但我不明白我如何使用上下文:this?

标签: jquery ajax html-table cell


【解决方案1】:

主要问题是 this 在 ajax 回调中有不同的上下文,而不是您期望从 each 循环中获得的元素实例

有几种方法可以解决this 的范围问题。

最不常用的方法是$.ajax 有一个context 选项

$('#mytable tbody').each(function () {
    $.ajax({
        /* other options left out for brevity*/
        context: this, // per docs "object will be made the context of all Ajax-related callbacks"
        success: function (return) {
            /* "this" is now the tbody instance*/
            $(this).find(".name").val(return.name);
        }
    });
});

更常见的方法是在调用$.ajax之前存储对元素的引用

$('#mytable tbody').each(function () {
    var $tbody = $(this); // store instance in variable
    $.ajax({
       /* other options */
        success: function (return) {
            $tbody.find(".name").val(return.name); 
        }
    });
});

就范围而言,第二种方法可能更容易阅读

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-08-07
    • 1970-01-01
    • 2018-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-23
    • 1970-01-01
    相关资源
    最近更新 更多