javascript - ajax调用未正确发送数据

标签 javascript jquery ajax node.js

我使用 ajax 调用的方式有问题。

当我将 ajax 调用放在 block 内时,它会执行 ajax 回调中的错误函数。当ajax调用移出 block 时,传递给服务器的变量subcate是未定义的。

var that = this;
var subCate ='' ;
var tr = $('#tbl').find('tr');

//My block
tr.bind('click', function(event) {
    var values = '';
    tr.removeClass('highlight');
    var tds = $(this).addClass('highlight').find('td');
    subCate = tds.find('#myid').text();
    alert(subCate);


      //Tried moving it out of the block but not much of help
        $.ajax({
            url: '/playground',
            type: 'POST',
            data: { id: subCate},
            success: function(data){
                alert("Sub category recvd");
                console.log("successs");
            },
            error: function(jqXHR){
                console.log("failed");
                alert("failed");
            }
        });
    });

    //Ajax call moved here

这是 Node.js 服务器代码:

  app.post('/playground', function(req, res) {
        debug("Inside post(/playground) ",req.body.id);
        res.send('ok', 200);
    });

嗨,这是 HTML 表格的片段,它可以让您了解 jquery 代码在做什么

<div id="category-container">
      <div id="category-form">
        <h1></h1>
        <p id="sub1" class="subheading">Select a category</p>
        <!--hr-->
        <div style="margin:20px" class="container">
          <table id="tbl" class="table table-bordered table-striped">
            <thead>
              <tr>
                <!--th(style='width:40px') #-->
                <th style="width:180px">Name</th>
                <th style="width:200px">Location</th>
                <th style="width:180px">Username</th>
              </tr>
            </thead>
            <tbody>
              <tr>
                <td>
                  <div id="myid"><a id="item" href="/playground/:0">Electronics</a></div>
                </td>
              </tr>
              <tr>
                <td>
                  <div id="myid"><a id="item" href="/playground/:1">Real Estate</a></div>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </div>

提前谢谢大家!

最佳答案

在绑定(bind)顶部添加 event.preventDefault()

此外,我建议将事件绑定(bind)更改为以下内容:

$('#tbl').on('click', 'tr', function(event) {
  event.preventDefault();
  // your code
});

关于javascript - ajax调用未正确发送数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18750742/

相关文章:

javascript - 如何将 Everything Website 从右到左转换为阿拉伯语,包括 JS 脚本?

javascript - React Native 等效于 React.createElement

javascript - 尝试将 SVG 签名转换为光栅图像

Jquery选项卡启用选项卡吗?

javascript - 遍历行以获取动态生成的输入值

javascript - 正则表达式获取每行的第一个元素

javascript - jqGrid 在使用 addRowData 时总是突出显示第一行

Jquery动画底部问题

javascript - 如何使用 jQuery 加载变量中的页面内容

jquery 不删除元素