Passing post parameters with jQuery.post
I have a regular anchor tag which is bound to a $.post() but I'm having trouble wrapping my head around the best way to pass along parameters. Here's what I've got:
<a
href="ajax/tag_delete.php?id=<?php echo $tag->id;?>" <!-- This feels too "GET" and I don't want to have to parse this query string -->
id="<?php echo $tag->id;?>" <!-- this feels wrong, shouldn't have a number as an id -->
class="delete_tag_btn">
delete
</a>
<script>
$('.delete_tag_btn').bind('click', function(event){
event.preventDefault();
$.post( this.href, {/* WHAT IS THE BEST WAY TO GET THESE */}, function(reply) {
log(reply);
开发者_StackOverflow中文版 });
});
</scirpt>
Any help is much appreciated. Thanks.
$(this).attr('href').split('=')[1]
Of course, that's dependent on your url having a single querystring parameter. If needed, you can get a little more fancy, but this solves your immediate problem.
Edit:
$(document).ready(function(){
$('.delete_tag_btn').bind('click', function(event){
event.preventDefault();
var s = $(this).attr('href').split('?')[1].split('&');
var a = new Object();
for(var n = 0; n < s.length; ++n)
{
var t = s[n].split('=');
console.log(String(t[0]));
a[String(t[0])] = t[1];
}
console.log(a);
});
});
Given the edit, you can specify any number of attributes in your href
, which will then be passed to your post
. In other words, you can use this function anywhere throughout your application and you don't need to specify which keys to get:
$.post(
this.href,
data: a,
function(reply) {
log(reply);
});
Actually, that should work. You might need to remove the empty object argument and switch to a .get call...
$.get(this.href, function(reply){
// Do whatever
});
On the other hand, you can always create an object...
var data = {
id: $(this).attr('id')
}
Then pass it in your .post call...
$.post(this.href, data, function(reply){
// Do whatever...
})
精彩评论