我正在编写一个 node.js 应用程序,我有点担心我如何构建发布数据以发送到服务器。例如,当我想删除一个数据项时,我把该项的 id 放在 href 属性中:
<a class='delete' href="1231">Delete this data</a>
<!-- href is based on a variable I'm pulling from the server -->
单击该链接时,我会阻止默认操作,然后运行 ajax 请求:
//On click + ajax
body.on('click', '.delete', function(e){
e.preventDefault();
$.ajax({
type: 'POST',
url: '/admin/report/detail/delete',
data: {id: $(this).attr('href')},
success: function(){
//Success message
},
error: function(){
//Error message
}
});
});
我想知道,以这种方式使用 href 属性是不是不好的做法?如果是这样,存储此数据的最佳方式是什么?
最佳答案
改用数据属性。将它们存储在 href 中不是语义的,如果您有时想存储 ID 而在其他时间存储其他数据怎么办?您可以根据需要创建任意数量的数据属性,并为它们指定语义名称。
<a class="delete" data-id="1231" href="#">
然后在你的 javascript 中:
...
data: { id: $(this).data('id') }
...
或
data: { id: $(this).attr('data-id') }
关于jquery - 在 href 中存储 POST 请求的数据 - 不好的做法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16108021/