Extjs4 note (3) Ext. Ajax support for Ajax

Source: Internet
Author: User
ArticleDirectory
    • 1. Send a custom request header for asynchronous requests:
    • 2. asynchronous request, return JSON:
    • 3. asynchronous file upload
    • 4. asynchronous request event
    • 1. Timely update of a single element
    • 2. submit a form for update
    • 3. Periodic updates
Back to the series directory

This article mainly introduces some extensions of JS syntax commonly used by extjs, including Ajax encapsulation, function event operation encapsulation, and common extended functions. The interactive operation on the Ajax server is submitted to. Net MVC. This method is used for subsequent server interaction.

I. Ajax in extjs: Ext. Ajax. Request

By sending an Ajax request to the server through a client, you can "directly" Call the MVC action method and PASS Parameters. the return value of an action can be a common string or a JSON object. You can add custom header information to a request. Take the following example:

1. Send a custom request header for asynchronous requests:

The HTML page is as follows:

[HTML]

 
<H1> Ajax Server Request  

We first trigger an Ajax request by clicking an event with a button. The server returns a string to the client. When an asynchronous request is sent, the server adds the custom Header "userheader" to the request and obtains it on the server. JSCode:

[JS]

 
Ext. onready (function () {New Ext. button ({renderto: "div1", text: "background Ajax submit", Handler: function () {Ext. ajax. request ({URL: 'ajax _ func1 ', headers: {'userhead': 'usermsg'}, Params: {A: 10, B: 20}, method: 'get', success: function (response, options) {Ext. messageBox. alert ('success', 'Get result from server: '+ response. responsetext) ;}, failure: function (response, options) {Ext. messageBox. alert ('failed', 'request timeout or network failure, error code: '+ response. status) ;}}) ;}, ID: "Bt1 "});});

The action code that the server MVC accepts the request:

[C #]

 
Public contentresult ajax_func1 (int A, int B) {string userheadermsg = convert. tostring (request. headers ["userheader"]); Return content (A + B ). tostring () + ", userheader:" + userheadermsg );}

Then we debug in Firefox: the custom request header has been added.

View execution results:

2. asynchronous request, return JSON:

To return JSON to the client, MVC needs to use Acton of jsonresult to automatically convert the C # object to JSON format. The client code is as follows:

[JS]

Ext. onready (function () {New Ext. button ({renderto: "div1", text: "backend Ajax submission method 2 Return JSON", Handler: function () {Ext. ajax. request ({URL: 'ajax _ func2 ', Params: {n: 10}, method: 'post', callback: function (options, success, response) {If (SUCCESS) {var responsejson = ext. JSON. decode (response. responsetext); Ext. MSG. alert ("successful", options. params. the factorial of N + "is: <font color = 'red'>" + responsejson. n1 + "</font> <Br/> "+ options. params. N + "is accumulated: <font color = 'red'>" + responsejson. n2 + "</font>");} else {Ext. MSG. confirm ('failed', 'request timeout or network failure, error no.: ['+ response. status + '] Do you want to resend it? ', Function (BTN) {If (BTN = 'yes') {Ext. ajax. request (options );}});}}});}});});

Server code:

[C #]

 
Public jsonresult ajax_func2 (int n) {int n1 = 1; int n2 = 0; For (INT I = 1; I <= N; I ++) {N1 * = I; n2 + = I;} var DATA = new {n1 = N1, N2 = n2}; return JSON (data, jsonrequestbehavior. allowget );}

To view the execution result, Let's first look at the debugging response result of Firefox and view the returned JSON content:

Interface execution result:

3. asynchronous file upload

Extjs uses powerful internal encapsulation to make Ajax requests seem to be able to directly submit binary stream data. Each time you submit file data, extjs automatically creates an IFRAME and submits it in IFRAME. After the submission is completed, it is automatically moved, and everything looks seamless. The following example shows an asynchronous request for refreshing file upload:

[HTML]

 
<H1> upload an Ajax file  

[JS]

// Upload the File Ext. get ("button1 "). on ("click", function () {Ext. ajax. request ({URL: "ajax_fileup", isupload: True, form: "form1", success: function (response) {Ext. messageBox. alert ("uploaded successfully, text file content:", response. responsetext );}});});

[C #]

 
Public contentresult ajax_fileup (httppostedfilebase file) {system. io. streamreader r = new system. io. streamreader (file. inputstream, system. text. utf8encoding. default); var STR = R. readtoend (); Return content (STR );}

After submission, we found that the content of the uploaded text file has been correctly read.

4. asynchronous request event

Before initiating an Ajax request, you can listen to the beforerequest event. In this example, every time an Ajax event is initiated, the calculator is + 1:

[JS]

VaR ajaxcount = 0; // triggered whenever an Ajax request is initiated: ext. ajax. on ('beforerequest ', function () {Ext. get ("span1 "). update (++ ajaxcount)}, this );

In this way, each time Ajax is initiated, it can be recorded and used as a log.

Ii. Ajax update of element objects: Ext. Updater, [Deprecated]

Extjs provides us with support for Asynchronously updating Dom element content. This can be used in some areas with strong Asynchronous interaction, such as webgame. Let's take a look at the specific implementation method.

First, we should write such HTML in the View:

[HTML]

 
<Div id = "div1" Title = "d1" style = "width: 50px; Height: 50px; position: absolute; Background-color: green; top: 100px "> 1 </div> <Div id =" div2 "> 2 </div> <Form ID =" form1 "> <input id =" A "name =" "value =" 20 "/> <input id =" B "name =" B "value =" 50 "/> </form>

1. Timely update of a single element

Now, I want to use C # to calculate the value of A + B on the server, and then fill in the result in the div1 element:

[JS]

Ext. Get ("div1"). getupdater (). Update ({URL: "ext/updaterfunc", Params: {A: 10, B: 3 }});

[C #]

 
Public contentresult updaterfunc (int A, int B) {return content ("A + B =" + (A + B ));}

After the page is loaded, div1 is automatically updated. Let's look at another method:

[JS]

 
Ext. get ("div1 "). load ({URL: "ext/updaterfunc", scripts: True, Params: {A: 10, B: 47}, text: "Please wait... "});

2. submit a form for update

[JS]

 
Ext. Get ("div1"). getupdater (). formupdate ("form1", "ext/updaterfunc ");

The results are the same, except that the submitted parameter comes from the form and the name of the parameter corresponds to the name value.

3. Periodic updates

[JS]

// Periodic update var up = new Ext. Updater ("div1"); up. startautorefresh (5, "ext/updaterfunc", {A: 10, B: 47 });

After this code is run, it updates div1 every five seconds to check the status of the server and client in a timely manner.

By Lipan)
Source: [Lipan] (http://www.cnblogs.com/lipan)
Copyright: The copyright of this article is shared by the author and the blog. The detailed link of this article must be noted during reprinting; otherwise, the author will be held legally liable.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.