Skip to content

Instantly share code, notes, and snippets.

@krutoo
Last active April 8, 2020 10:07
Show Gist options
  • Save krutoo/ced5b63059bc93f4e33c4fde32eef201 to your computer and use it in GitHub Desktop.
Save krutoo/ced5b63059bc93f4e33c4fde32eef201 to your computer and use it in GitHub Desktop.
Simple AJAX helper (not checked)
export const ajax = (url, {
method = 'GET',
contentType = 'application/x-www-form-urlencoded; charset=UTF-8';
data,
onDone,
} = {}) => {
const xhr = new XMLHttpRequest();
if (typeof onDone === 'function') {
const handler = () => onDone(xhr);
xhr.onload = handler;
xhr.onerror = handler;
}
xhr.open(method, url, true);
xhr.setRequestHeader('Content-Type', contentType);
xhr.send(contentType ? data : objectToURL(data));
}
export const objectToURL = (value, key) => {
const list = [];
const isPrimitive = value !== Object(value);
if (!isPrimitive) {
for (const index in value) {
const parameterName = key
? `${key}[${Array.isArray(value) ? '' : index}]`
: index;
list.push(`${objectToURL(value[index], parameterName)}`);
}
} else {
value = encodeURIComponent(value);
list.push(key ? `${encodeURIComponent(key)}=${value}` : value);
}
return list.join('&');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment