Запрос POST (Javascript)
Как вы делаете простой запрос POST в Javascript без использования форм и без отправки?
Ответы
Ответ 1
Хотя я беру образец кода из ответа @sundeep, но размещаю здесь код для полноты
var url = "sample-url.php";
var params = "lorem=ipsum&name=alpha";
var xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
//Send the proper header information along with the request
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send(params);
Ответ 2
Я создал функцию, которая отправляет запрос без обновления страницы, не открывая страницы и без AJAX. Прогресс невидим для пользователя. Я использую false iframe для отправки запроса:
/**
* Make a request without ajax and without refresh the page
* Invisible for the user
* @param url string
* @param params object
* @param method string get or post
**/
function requestWithoutAjax( url, params, method ){
params = params || {};
method = method || "post";
// function to remove the iframe
var removeIframe = function( iframe ){
iframe.parentElement.removeChild(iframe);
};
// make a iframe...
var iframe = document.createElement('iframe');
iframe.style.display = 'none';
iframe.onload = function(){
var iframeDoc = this.contentWindow.document;
// Make a invisible form
var form = iframeDoc.createElement('form');
form.method = method;
form.action = url;
iframeDoc.body.appendChild(form);
// pass the parameters
for( var name in params ){
var input = iframeDoc.createElement('input');
input.type = 'hidden';
input.name = name;
input.value = params[name];
form.appendChild(input);
}
form.submit();
// remove the iframe
setTimeout( function(){
removeIframe(iframe);
}, 500);
};
document.body.appendChild(iframe);
}
Теперь вы можете сделать это:
requestWithoutAjax('url/to', { id: 2, price: 2.5, lastname: 'Gamez'});
Посмотрите, как работает!: http://jsfiddle.net/b87pzbye/10/.
Ответ 3
Вы можете сделать это, используя вызовы AJAX (объект XMLHttpRequest)
http://www.openjs.com/articles/ajax_xmlhttp_using_post.php