Nested XMLHttpRequest calls? (Cleaning this code up?)


Nested XMLHttpRequest calls? (Cleaning this code up?)

I'm creating a script to run on a page. This page has a few ajax calls, each of them being sequential (if A works, make call B, etc).

My code:

function doSomething(element) { var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { pageCheck(this,element); } } xhr.open('GET', URL); xhr.responseType = 'document'; xhr.send(); } 

Inside pageCheck, I pass element (doesn't matter what it is) and the dom object obtained through that xmlhttprequest call. Inside pageCheck I have another series of

pageCheck(page,item) { var xhr1 = new XMLHttpRequest(); xhr1.onreadystatechange = function() { if (...) { doSomethingElse(..); } xhr1.open(..) xhr1....etc } 

My issue is, this looks horrible. Can't I make some wrapper for the XML requests? I had this, but realized I can't access the xhr object. How can I clean this up without fetch, jquery, promises, etc? Re-use the xhr object?

function XMLWrapper(url) { var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { pageCheck(this,item); } } xhr.open('GET', url); xhr.responseType = 'document'; xhr.send(); } 

Submitted July 17, 2017 at 06:08PM by -Kevin-
via reddit http://ift.tt/2u0yDMG

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s