简体   繁体   English

ajax调用未正确发送数据

[英]ajax call not sending data correctly

There is something wrong with the way I am using the ajax call. 我使用ajax调用的方式出了点问题。

When I place the ajax call inside the block, it executes the error function in the ajax callback. 当我将ajax调用放置在代码块中时,它将在ajax回调中执行错误功能。 When the ajax call is moved outside the block, the variable subcate passed to server is undefined. 当ajax调用移到该块之外时,传递给服务器的变量子类别是未定义的。

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

Here is the node.js server code : 这是node.js服务器代码:

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

Hi Here is the snippet of HTML table, that will give an idea what the jquery code is doing 嗨,这是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>

Thanks in advance guys ! 在此先感谢大家!

Add event.preventDefault() at the top of your bind. 在绑定的顶部添加event.preventDefault()

Also, I recommend changing the event binding to the following: 另外,我建议将事件绑定更改为以下内容:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM