我使用 ajax 调用的方式有问题。
当我将 ajax 调用放在块内时,它会在 ajax 回调中执行错误函数。当 ajax 调用移到块外时,传递给服务器的变量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>
提前谢谢你们!