📅  最后修改于: 2022-03-11 15:04:13.996000             🧑  作者: Mango
function postAjax(url, data, success) { var params = typeof data == 'string' ? data : Object.keys(data).map( function(k){ return encodeURIComponent(k) + '=' + encodeURIComponent(data[k]) } ).join('&');
var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP"); xhr.open('POST', url); xhr.onreadystatechange = function() { if (xhr.readyState>3 && xhr.status==200) { success(xhr.responseText); } }; xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xhr.send(params); return xhr;}
// example requestpostAjax('http://foo.bar/', 'p1=1&p2=Hello+World', function(data){ console.log(data); });
// example request with data objectpostAjax('http://foo.bar/', { p1: 1, p2: 'Hello World' }, function(data){ console.log(data); });