Jquery $.post() - Possible to do a full page post request?
I know I can do an out of band Post request with jQuery and the $.post()
syntax. However, I'm interested to know if it is possible for jQuery to cause开发者_运维技巧 a post request on the whole page (as when a form is submitted) so that a brand new page is loaded. Is this possible?
There is no form element in the DOM, so I can't do form.submit().
I use this function when I need to send data and don't have form in the DOM:
function postData(actionUrl, method, data) {
var mapForm = $('<form id="mapform" action="' + actionUrl + '" method="' + method.toLowerCase() + '"></form>');
for (var key in data) {
if (data.hasOwnProperty(key)) {
mapForm.append('<input type="hidden" name="' + key + '" id="' + key + '" value="' + data[key] + '" />');
}
}
$('body').append(mapForm);
mapForm.submit();
}
And I call it like this:
var data= { 'property1': 666, 'property2': 'I am a boy' };
postData('http://urltopostdata.to', 'post', data);
Think this plugin should do the trick: http://www.mimiz.fr/javascript/jquery/en-jquery-postdatas-plugin/?lang=en
Not sure if I got your question, but if you just want to redirect the client after posting, just direct the client in the callback function of the $.post like
jQuery.post( url, {}, function() { location.href = "somewhere_else.html"; } )
I think you're trying to re-implement the default behaviour. Just use the regular submit mechanism the browser provides.
If you need to check the data before you actually submit it to the server, bind a function to the onsubmit event and do your checks, then either interrupt the submit action by returning false or return true and let the browser do all the work. Does this make sense to you?
I've used the following example to allow multiple buttons to submit serialized form data but with different options, e.g. Save and Save & Close. Even though I'm using jQuery to post serialized data the whole page reloads because i'm sending the ajax post response data back to "document.body".
<form id="myform">
<button id="button1" type="button" onclick="submitButton(true,false)" name="save" value="save">Save</button>
<button id="button1" type="button" onclick="submitButton(true,true)" name="close" value="close">Save and Close</button>
</form>
function submitButton(save,close) {
$.ajax({url:'page.asp', data:''+$('#myform').serialize()+'&save='+save+'&close='+close+'',
type: 'post',
success: function(data){$(document.body).html(data);}
});
}
You don't need a form element as you can use this with any element that has a unique id.
精彩评论