ajax调用没有正确发送数据

时间:2013-09-11 20:35:13

标签: javascript jquery ajax node.js

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

当我在块中放置ajax调用时,它会执行ajax回调中的error函数。当ajax调用移到块外时,传递给服务器的变量 subate 是未定义的。

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>

先谢谢你们!

1 个答案:

答案 0 :(得分:0)

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

另外,我建议将事件绑定更改为以下内容:

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