How can I minimize the repetition of code with this jquery ajax?
I have many functions on a page, where the following code is exactly the same, except for the data being sent, and the success div to display the result to. For example:
One ajax post:
$.ajax({
type: 'POST',
url: 'unique_file.php',
data: {qty: 2, item_id: 13},
cache: false,
success: function(data) {
$('#return_div').html(data);
}
});
Another ajax post:
$.ajax({
type: 'POST',
url: 'another_unique_file.php',
data: {no_shipping: 4},
cache: false,
success: function(data) {
$('#a_differen开发者_如何学Got_div').html(data);
}
});
So I was thinking it would be ideal to make this into a function like so
function do_ajax(post_file,results_div,post_data) {
$.ajax({
type: 'POST',
url: post_file,
data: {post_data}, // this doesn't appear to work
cache: false,
success: function(data) {
$(results_div).html(data);
}
});
}
Then I can achieve #1 ajax like so:
do_ajax('unique_file.php','#return_div','qty: 2, item_id: 13');
This seems logical to me, but the limits of my logic are how to get the data into my function. Perhaps the post_data is not just a string like that but more something like:
do_ajax('purchase_create.php','#create_purchase_window','item_id:'+$item_id+', qty: '+$qty+'');
Which looks pretty messy... but mostly, it just doesn't work. Is there a cleaner way of perhaps putting all the data into an array and giving that to the function?
You can use ajaxSetup to set defaults.
$.ajaxSetup({
cache: false,
type: 'POST'
});
then
$.ajax({
url: post_file,
data: {post_data: post_data}, // this doesn't appear to work
success: function(data) {
$(results_div).html(data);
}
});
{post_data}
is not correct syntax. So I changed it to {post_data: post_data}
You're on the right track:
function do_ajax(post_file,results_div,post_data) {
$.ajax({
type: 'POST',
url: post_file,
data: post_data,
cache: false,
success: function(data) {
$(results_div).html(data);
}
});
}
do_ajax('purchase_create.php, '#create_purchase_window', {
item_id: 3,
qty: 2
});
You're passing an object to POST
, so just pass that object into your do_ajax
function and pass it along.
精彩评论