Created
October 4, 2018 10:52
-
-
Save aiiddqd/80874fd76be15a0881f1a234c6f9744d to your computer and use it in GitHub Desktop.
AJAX wrapper for native JavaScript and WordPress REST API
This file contains hidden or 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
/** | |
* AJAX обертка для WordPress REST API | |
*/ | |
let sb_ajax = function ( ep, success, error, type = 'GET', data = '' ) { | |
url = wpApiSettings.root + ep; | |
// Feature detection | |
if ( !window.XMLHttpRequest ) return; | |
// Create new request | |
var request = new XMLHttpRequest(); | |
// Setup callbacks | |
request.onreadystatechange = function () { | |
// If the request is complete | |
if ( request.readyState === 4 ) { | |
// If the request failed | |
if ( request.status !== 200 ) { | |
if ( error && typeof error === 'function' ) { | |
error( request.responseText, request ); | |
} | |
return; | |
} | |
// If the request succeeded | |
if ( success && typeof success === 'function' ) { | |
success( request.responseText, request ); | |
} | |
} | |
}; | |
// Get the HTML | |
request.open( type, url ); | |
if(type != 'GET'){ | |
request.setRequestHeader("Content-Type", "application/json;charset=UTF-8"); | |
} | |
request.setRequestHeader("X-WP-Nonce", wpApiSettings.nonce); | |
if(data){ | |
request.send(JSON.stringify(data)); | |
} else { | |
request.send(); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment