jquery how to send json data to multiple links?
I have this code:
$.ajax({
type: "POST",
data: JSON.stringify(formData),
dataType: "json",
url: "http://www.test.com/users/" + get_back + "",
success: function(t){
alert(t);
}
});
I was wondering ho开发者_Go百科w can I POST to multiple links? Do I have to create another $.ajax POST
or can I just add more url
fields into the same POST?
Thanks
You have to do it multiple times, one for each URL you want to send to. But there are shortcuts:
var urls = ["http://www.test.com/users/", "http://www.example.com/users/", "http://www.test.org/users/"]
$.each(urls, function(index, value) {
$.ajax({
type: "POST",
data: JSON.stringify(formData),
dataType: "json",
url: value + get_back + "",
success: function(t){ alert(t); }
});
});
We are putting all the URLs you want to POST to in a JavaScript Array and then using jQuery's $.each to iterate through them and do an AJAX POST to each one.
You cannot add additional mode fields. JavaScript object literals (e.g. {foo:'bar'}
) can only have one value for each key. Browsers tend to interpret {url:'http://example.com', url:'http://example.com/page2'}
as {url:'http://example.com/page2'}
.
jQuery's ajax functionality only sends a single ajax request. The following code will let you create a default request object, and overwrite its members as you see fit:
function createAjaxer(o) {
var defaults = $.extend({}, o);
return {
send: function(o2) {
var instance = {};
$.extend(instance, defaults, o2);
$.ajax(instance);
}
}
}
You can use it as follows:
var a = createAjaxer({
type: 'post',
dataType: 'json',
success: function() { console.log(arguments); }
});
a.send({
data: 'yar=5',
url: 'http://stackoverflow.com'
});
a.send({
url: 'http://stackoverflow.com'
});
This allows you to set sensible defaults. And the basic idea is reusable for all sorts of purposes.
You must do separate calls for each URL, try using $.each to call the same code multiple times.
精彩评论