ajax.js 687 B

123456789101112131415161718192021222324
  1. function postJson(url, data, callback) {
  2. var r = new XMLHttpRequest();
  3. r.open("POST", url, true);
  4. r.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  5. r.onreadystatechange = function () {
  6. if (r.readyState != 4 || r.status != 200) return;
  7. var response = JSON.parse(r.responseText);
  8. callback(response);
  9. };
  10. r.send(urlparams(data));
  11. }
  12. function urlparams(obj, prefix) {
  13. var str = [], p;
  14. for(p in obj) {
  15. if (obj.hasOwnProperty(p)) {
  16. var k = prefix ? prefix + "[" + p + "]" : p, v = obj[p];
  17. str.push((v !== null && typeof v === "object") ?
  18. serialize(v, k) :
  19. encodeURIComponent(k) + "=" + encodeURIComponent(v));
  20. }
  21. }
  22. return str.join("&");
  23. }