Tech tip of this week

Sencha Touch: AJAX Request

A singleton instance of an Ext.data.Connection. This class is used to communicate with your server side code.

Because of browser security restrictions, AJAX requests are usually made to urls on the same domain as your application.

Ext.Ajax.request({ 

                url: 'myUrl', 
                callback: function(options, success, response) 
                { 
                           console.log(response.responseText); 
                } 
});

Ext.Ajax takes a wide variety of options, including setting the method (GET, POST, PUT, or DELETE), sending headers, and setting params to be sent in the url. 

Ext.Ajax.request({ 
                 url: 'myUrl', 
                 params: { 
                            username: 'ABC', 
                            password: 'XYZ' 
                 }, 
                 callback: function(options, success, response) 
                 { 
                            console.log(response.responseText); 
                 } 
});

sending headers:

Ext.Ajax.request({ 
                 url: 'myUrl', 
                 headers: { 
                              "Content-Type": "application/json" 
                 }, 
                 callback: function(options, success, response) 
                 { 
                           console.log(response.responseText); 
                 } 
});

callback options:

Ext.Ajax.request({ 
                 url: 'myUrl', 
                 success: function(response) { 
                          console.log("Spiffing, everything worked"); 
                 }, 
                 failure: function(response) { 
                          console.log("Curses, something terrible happened"); 
                 } 
});

Cross Domain Requests:

CORS, which stands for Cross-Origin Resource Sharing. This allows you to send requests to other domains, without the usual security restrictions enforced by the browser.
Sencha Touch provides support for CORS, although you will probably need to configure your web server in order to enable it
Assuming your server is set up, sending a CORS request is easy:

Ext.Ajax.request({ 
            url: 'http://www.somedomain.com/some/awesome/url.php',              
            withCredentials: true, 
            useDefaultXhrHeader: false 
});

No comments:

Post a Comment