我使用 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/