Last active
April 8, 2020 10:07
-
-
Save krutoo/ced5b63059bc93f4e33c4fde32eef201 to your computer and use it in GitHub Desktop.
Simple AJAX helper (not checked)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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