Server Agent (proxy)

Source: Internet
Author: User

Ajax

In Web application development, Ajax is the most common technique used to interact with the server side. Ajax is the use of JavaScript to create a HttpRequest, asynchronous way to get data from the server. Let's look at a simple example:

Ext.onready (function() {Ext.define (' Person ', {extend:' Ext.data.Model ', fields: [' Name ', ' age ']    }); varstore = ext.create (' Ext.data.Store ', {model:' Person ', Proxy: {type:' Ajax ', Url:rooturl+ ' Sample/getjson ', Reader: {type:' JSON ', Root:' Users '            }        }    });    Store.load (); varmsg = []; Store.each (function(person) {Msg.push (Person.get (' name ') + ' + person.get (' age '));    }); Ext.MessageBox.alert (' Hint ', msg.join (' <br/> '));});

In this code, the model class person is defined first, and then the data warehouse for the person class is created Store,store uses an AJAX proxy to request data from the server via a URL, and the AJAX Agent reader A configuration item is a method that tells the program how to read the requested data.

The JSON string we return from the server is as follows:

{users:[{name: ' www.qeefee.com ', age:1}, {name: ' Tom ', age:26}]}

Let's start by guessing the results of the operation. According to the logic in the previous section, a dialog box should pop up here, showing the contents of the content, but the actual run time to get the empty content, as follows:

Did we not ask for the data? Of course not, if you turn on the network Trace, you will find that the program has successfully obtained this JSON string. Why is it still empty?

The reason is that when we call the load () method, we tell the store to request the data, and then the store uses AJAX to request the URL, noting that Ajax is asynchronous, so when we call the load () method, the store is still empty when we execute the output immediately. It may also be waiting for the server to respond to data.

Therefore, when we use AJAX to load the data, we need to add a callback method to the load () method, when the data is loaded, then the data output in the callback method, modify the Load method call:

store.load ({    function  (records, operation, success) {        if  (success) {             var msg = [];            Store.each (function  (person) {                Msg.push ("Person.get (' name ') + ' + person.get (' age ') ));            });            Ext.MessageBox.alert (' hint ', msg.join (' <br/> ');}        }    );

Refresh the page, this is the result we want:

Ajax request with parameters

We turn on web tracking, refresh the page, and track all our network requests:

To find Getjson's request, click View Details:

As you can see in this URL, ExtJS has actually added some parameters to us, including page, start, and limit. Where did these parameters come from?

When using Ajax for a request, the AJAX proxy invokes its own read method whose first parameter is the Ext.data.Operation type, which is used to configure how we make the request. We can pass some parameters in the Load method through configuration items, and load passes those arguments past when the Read method is called, and read generates an instance of Ext.data.Operation based on these parameters. So, we can pass parameters like this:

 store.load ({page:  2 10 Span style= "color: #000000;" >, params: {name:  ' QF '   ' hint ', msg.join (' <br/> ' 

We tracked the request again, and the address passed into/sampleextjs/sample/getjson?_dc=1374141754304&name=qf&page=2&start=25&limit=. 10

By passing these parameters, we can do the paging, query and so on.

JsonP

In JavaScript, because of the serious security implications of cross-domain operations, browsers do not allow us to use Ajax directly for cross-domain requests. When using cross-domain requests, we can use the form of request JavaScript resources to load the requested JSON data into the browser as JavaScript code (the browser does not block cross-domain resource requests, including JavaScript, CSS, pictures, and so on). How to do this: dynamically add a script tag using Javascript, pass the requested resource URL as a property of SRC (the parameter that usually contains a callback method name in the request URL), wrap the requested data on the server side, and then return it to the client.

In ExtJS we can easily use the JSONP proxy for cross-domain data requests:

// Create store var store = ext.create (' Ext.data.Store ',{    ' person ',    proxy: {        ' Jsonp ',         ' Http://www.abc.com/sampleextjs/sample/getjsonp ',        reader: {            ' json ',            Root:' users '}}    );

In the test, our native name is localhost, so the data request to the domain name abc.com is a cross-domain operation (we have modified the native Hosts file in the Bootstrap.js of section II, and will abc.com also point to local).

Then add the server segment code and add the Getjsonp method to the Samplecontroller:

Public string Getjsonp () {    = request["callback"];     if (String. IsNullOrEmpty (callback))        = "callback";     = "Text/javascript";     return callback + "({users:[{name: ' www.qeefee.com ', age:1}, {name: ' QF ', age:26}]})";

In this code, we first get the callback parameter in the request, and if not, the default is the "callback" string. Then pass the stitched JSON string as a parameter to the callback method, and the string we return here follows the JavaScript syntax.

Compile the project, refresh the page, open the Developer tool, track the network request, and you will find that when making a network request, ExtJS automatically adds a callback method to the request address, which contains the parameters: callback= Ext.data.JsonP.callback1, according to the incoming callback parameter, the string returned by our server is:

Ext.data.JsonP.callback1 ({users: [{name: ' www.qeefee.com ', age:1}, {name: ' QF ', age:26}]})

This code can be used as JavaScript code to execute after the load is complete. The results of our operation

This approach provided by ExtJS greatly simplifies the processing of our clients ' code, allowing us to make JSONP cross-domain requests.

JSONP Agent's other operations with the AJAX agent basically has been, no longer introduce too much. Next, look at the rest agent.

Rest

What does Rest refer to? According to my own understanding, I think rest is a development specification, because HTTP requests are stateless, so when requesting for network resources, we usually pass the state (the operation to be performed: Add and delete, and the data to be manipulated) as parameters to the server, while rest provides that HttpMethod get, POST, put, delete correspond to different actions (get corresponding lookup, PUT corresponding update, POST corresponding to new, delete corresponding delete). For more complete rest, please refer to "in layman's Rest".

in ASP. NET MVC, we can use the Web API to easily implement restful applications.

We first define a model in the server segment with C # code:

Public class user{public    string name {get; set;}     int Age {get; set;}}

Then create a usercontroller for the user class operation, which needs to inherit from Apicontroller, with the following code:

 Public classusercontroller:apicontroller{ Public StaticList<user> userlist =NULL; StaticUsercontroller () {if(UserList = =NULL) {userlist=NewList<user>(); Userlist.add (NewUser () {name ="www.qeefee.com", age =1 }); Userlist.add (NewUser () {name ="QF", age = - }); }    }    //GET api/<controller>     PublicList<user>Get () {returnuserlist; }    //GET API/<CONTROLLER>/5     PublicList<user> Get (stringname) {List<User> result =NewList<user>(); foreach(User Iteminchuserlist) {            if(Item.name = =name) result.        ADD (item); }        returnresult; }    //POST api/<controller>     Public voidPost ([frombody]user user) {userlist.add (user); }    //PUT API/<CONTROLLER>/5     Public voidPut ([frombody]user user) {userlist.add (user); }    //DELETE API/<CONTROLLER>/5     Public voidDelete (stringname) {         for(inti = Userlist.count-1; I >=0; i--) {User User=Userlist[i]; if(User.Name = =name)            {userlist.removeat (i); }        }    }}

Since the API chooses different actions for different httpmethod, when we use the browser to request the API directly, we will get the result of the first get method:

Since we do not specify the format of the returned data, the default is for us to convert the object to XML. We use the rest agent in ExtJS:

// Create store var store = ext.create (' Ext.data.Store ', {    ' person ',    proxy: {        ' rest ',         + ' api/user/',        reader: {            ' json '}}}    ;

Then load the data using the Load method:

store.load ({    function  (records, operation, success) {        var msg = [];        Store.each (function  (item) {            Msg.push (' Item.get (' name ') + '   + item.get (' Age ') );        });        Ext.MessageBox.alert (' hint ', msg.join (' <br/> ');    }});

The network request is tracked at this time:

The red box is a preview of the URL we requested and the data we got. We will be prompted when the program finishes parsing:

At this point we can perform some crud operations on the store, track network requests and server segment code, and see how the rest agent works.

Direct

The Direct agent uses Ext.direct to send data to the server.

The benefit of Ext.direct technology is that it allows you to invoke server-side code just as you would call JavaScript methods. We will introduce ext.direct in detail in a later chapter. After we have defined ext.direct, we can use the Direct proxy to request data.

For example, the code we see in the API:

Ext.define (' User ', {    ' Ext.data.Model ', fields    : [' firstName ', ' LastName '],    proxy : {        ' direct ',        directFn:MyApp.getUsers,        //  tells the proxy to pass the ID as th E first parameter to the remoting method.     }}); User.load (1);

Server Agent (proxy)

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.