Multiple post requests and small web server
I have a problem with a small web server with limited resources:
The device is an embedded controller with network interface and uses web pages for configuration.
The data are exchanged with
json
format and the post method.
The problem is this: my device can serve only one post request at a time with a small buffer size.
To test it, I created a page with multiple posts for sending data to my server. I opened the page with the browser Firefox 4.0 and the browser tried to open multiple socket to serve all requests in parallel.
How do I create a sequential flow message? (I'm not worried about the speed)
Here is a small example of how I intend to proceed, but this solution opens two sockets for sending two post requests to my server and aborts one of them.
for (var j=0; j<2; j++) {
// read page data and create objdata
开发者_开发百科 jdata = JSON.stringify(objdata);
// alert("I am about to POST this:\n\n" + jdata);
$.post(
'prgtimetbl.json',
jdata,
function(data) {
// alert("Response: " + data);
},
"json"
);
}
With jQuery use $.ajax and async: false
:
$.ajax({
type: "POST",
url: "some.php",
async: false,
data: "name=John&location=Boston",
success: function(msg){
alert( "Data Saved: " + msg );
}
});
Cixate was faster than me, but I had a slightly different approach using async queued requests.
Sample: http://jsfiddle.net/HTGPM/
Code:
$(document).ready(function(){
var stuffToPost = [{name:'obj1',id:1},{name:'obj2',id:2},{name:'obj3',id:3}];
var postIndex = 0;
var postNext = function() {
if (postIndex < stuffToPost.length)
{
$.ajax({
type: 'post',
url: '?',
data: JSON.stringify(stuffToPost[postIndex]),
success: function(data) {
alert('Data '+stuffToPost[postIndex].id+' was sent successfully');
postIndex++;
postNext();
},
error: function() {
alert('Something bad happened. Stopping');
}
});
}
else if (postIndex == stuffToPost.length)
{
alert('All data is sent !');
}
};
postNext();
});
精彩评论