For details about how to use angularjs and ajax, angularjsajax

Source: Internet
Author: User

For details about how to use angularjs and ajax, angularjsajax

This is an article about easyui and ajax. It introduces the use of angularjs and the power of angularjs. Ajax is also widely used on the Internet. I won't write it directly from the js of the native httpxmlrequest object. The essence of this kind of thing is to understand how high-level things come about. What is the principle of writing things in real time? Isn't it a nonsense? Are you using your technical skills to write the whole site?. When html js was first designed, it was just a waste of research. Fortunately, there are various frameworks that can help us make it easier and more delicious. It is also better that the Internet industry is driving the development of such a pile of items on the browser side in a unified and standardized direction.

Let's create a webform page HelloAjaxNet. aspx. Let's talk about ajax here I use the AjaxPro.2.dll which is widely spread on the Internet. His website is is a personal work, it is very useful.

In the new, the server method uses the webmethod attribute to declare the client pagemethods access method. Various objects can also be json-formatted with the same functions as above. Microsoft's codebehind code method of aspx must be static, as for webconfig in the new version of vs2013 development environment, you do not need to configure it. If it is old, the new ajax website project will be automatically completed by webconfig and then the Server Page will load ScriptManager in the event. getCurrent (Page ). enablePageMethods = true; the client must have the form and <asp: ScriptManager ID = "ScriptManager1" runat = "server"> </asp: scriptManager> then the client can access it through pagemethods.

I always think the one above is better. I will not talk much about his principle. register the server object when loading the page, and then the generated html page contains a few more words.

 <script type="text/javascript" src="/ajaxpro/prototype.ashx"></script> <script type="text/javascript" src="/ajaxpro/core.ashx"></script> <script type="text/javascript" src="/ajaxpro/converter.ashx"></script> <script type="text/javascript" src="/ajaxpro/WebApplication.StudentsInfo,WebApplication.ashx"></script> <script type="text/javascript" src="/ajaxpro/WebApplication.Grad,WebApplication.ashx"></script> <script type="text/javascript" src="/ajaxpro/WebApplication.NewFolder.HelloAjaxNet,WebApplication.ashx"></script> <script type="text/javascript" src="/ajaxpro/WebApplication.DataEntity,WebApplication.ashx"></script>

For reference to a js file ajaxpro/WebApplication1.NewFolder2. HelloAjaxNet, WebApplication1.ashx

Then you will understand that the script for calling client js is automatically generated by the server and the name of the server is exactly the same as that of the server. Then you can look like there is nothing like a callback method on the client server. amazing, we mainly want to use this feature and the convenience of json data to achieve seamless data transfer on the client server.

For the serialization of json data, only the external json library or the built-in Microsoft can be used for manual parsing:


public string ServerProcerMethod(string stu)     {       //System.Web.Script.Serialization.JavaScriptSerializer jsSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();       //StuInfo s= jsSerializer.Deserialize<StuInfo>(stu);        System.Web.Script.Serialization.JavaScriptSerializer jsSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();       List<StuInfo> s = jsSerializer.Deserialize<List<StuInfo>>(stu);       if (s != null && s.Count > )       {         StuInfo stu= s[];         StringBuilder sb = new StringBuilder();         jsSerializer.Serialize(stu, sb);         return sb.ToString();       }       else         return null;     }


// Convert javascript strings to json objects: var obj = JSON. parse (str); // convert javascript json objects to strings: JSON. stringify (obj );

About the relationship between AjaxPro.2.dll and ajax. dll, the Internet says that they are different, but they are actually done by a person. Download the ajaxpro version from the website above.

After referencing the dll file, you need to configure webconfig httphandler to transfer the above ashx request to our ajaxpro code, so that our client js can directly call the server method call successfully.

<system.webServer>   <directoryBrowse enabled="true"/>   

Then I will not talk about anything else. I will directly look at the server code later.

Easyui can be understood as a bunch of extended controls. Just like jquery, you can use the JavaScript Object's native html control with a pack of other things to figure out some of the methods he has written for you to help you easily process data. There is also a default control appearance that can also be used, which is really good for enterprise management software. If you do anything else, you can only do it. Download the easyui file and put it in the project. Introduce js and style files related to easyui and jquery:

<script type="text/javascript" src="../jquery-easyui-../jquery.min.js"> </script>   <link rel="stylesheet" type="text/css" href="../jquery-easyui-../themes/default/easyui.css" />   <link rel="stylesheet" type="text/css" href="../jquery-easyui-../themes/icon.css" />   <script type="text/javascript" src="../jquery-easyui-../jquery.easyui.min.js"></script>

Then, you can use easyui, as described on the easyui homepage, to render the native html controls into easyui controls through css styles or js Code.

 <div class="easyui-dialog" style="width:px;height:px"   data-options="     title:'My Dialog',     iconCls:'icon-ok',     onOpen:function(){}">   dialog content. </div> <input id="cc" style="width:px" /> $('#cc').combobox({   url: ...,   required: true,   valueField: 'id',   textField: 'text' });

Yes, it is very convenient. In fact, there are still a lot of js writers in China who have made some ui such as this to choose the ui or use this. The most commonly used requirement is the ajax server paging. Let's get it.

Let's talk about this easyui datagrid hitting his dog's Day. The client html puts a table Tag: <table id = "studb"> </table> and then use js for $ ('# studb '). the datagrid () is rendered to the easyui datagrid Control. ready. Our data table is where the data needs to be filled with data to show which columns, how many lines are displayed on each page, and how these parameters are passed in. Easyui receives parameters in the json object format in many places, such as the datagrid:

Function bindDataToTb () {var keywordStr = $ ('# keyword '). val (); $ ('# studb '). datagrid ({queryParams: {keyword: keywordStr}, // url: "WebForm. aspx/BindData ", toolbar: '# searchbar', pagination: true, pageNumber:, singleSelect: true, pageSize:, pageList: [,], loader: function (param, success, error) {var da = WebApplication. newFolder. helloAjaxNet. bindData (param. keyword, param. page, param. rows) if (da. value. rows = null) {success ();} else success (da. value) ;}, pagePosition: 'bottom ', columns: [{field: 'std', title: 'id', width:}, {field: 'name ', title: 'name', width :},{ field: 'age', title: 'age', width :},{ field: 'loginname', title: 'login name ', width :}, {field: 'loginpwd', title: 'Password', width :}, {field: 'gradid', title: 'class id', width :}, {field: 'gradname', title: 'class', width:}, {field: 'none', title: 'operation', width:, formatter: function (value, row, index) {var btn = '<a class = "editcls" href = "#" onclick = "delstuClick (' + row. stuNo + ') "> Delete </a>'; return btn ;}}]});}

For more information, see loader and columns. loader is used to define the form in which you load data and define the url above loader.

Here, WebApplication1.NewFolder2. HelloAjaxNet. BindData (param. keyword, param. page, param. rows) is also a server-side method for data retrieval.

The three param. keyword, param. page, And param. rows are parameters that we intentionally expose to us when implementing easyui when loader.

Param. keyword is the query keyword queryParams: {keyword: keywordStr}

Param. page is the parameter of easyui, indicating the current page of param. rows indicates the number of rows per page. When you click the previous page on the next page of the table, the system automatically sends a page turning parameter to loader.

Then we can get the data filling table from the server, which is such a work process. In addition, colums is easy to understand.

The easyui control has an attribute method. The Calling method is like this: $ ('# studb '). datagrid ('reload') is equivalent to calling the reload method of the # studb table control, and then the data is automatically refreshed. For details about each control, see the document.

We still use entityframework for server-side data processing. I usually use codefirst to integrate it with its own mssql database.

Server code:

// Query (with paging [AjaxPro. ajaxMethod] public static WebApplication. dataEntity BindData (string keyword, int page, int rows) {//, ref int pageIndex, out int totalPage if (keyword = null) keyword = ""; int pageIndex =; int pageSize =; int totalPage; if (page! =) PageIndex = page; if (rows! =) PageSize = rows; MyDb db = new MyDb (); var data = from studentInfo in db. students where studentInfo. name. contains (keyword) select new {stuNo = studentInfo. stuNo, name = studentInfo. name, age = studentInfo. age, gradName = studentInfo. grad. gradName}; // var data = from studentInfo in db. students where studentInfo. name. contains (keyword) select studentInfo; totalPage = data. count () % pageSize =? Data. count ()/pageSize: data. count ()/pageSize +; if (pageIndex> totalPage) pageIndex = totalPage; else if (pageIndex <) pageIndex =; // var dt = DataList <object>. create (data. orderBy (r => r. stuNo), new StudentsInfo (), pageIndex, pageSize ). value; object dt = null; if (data. count ()>) dt = DataList <object>. create (data. orderBy (r => r. stuNo), new {stuNo =, name = "", age =, gradName = ""}, pageIndex, pageSize ). value; WebApplication. dataEntity result = new WebApplication. dataEntity (); result. total = data. count (); result. rows = dt; return result ;}

I will not post the data section and the EF linq page for the complete example download. Let's take a look. You can try it without refreshing the pages on the new server. It feels great.


I don't want to say anything about searching. I just need to re-load the data. Deleting is to upload the id to the js function using a Custom column and then call the server to delete it. Next, let's talk about the input function and form verification provided by easyui.

Create a new div as the pop-up layer. There is a table with information input. All kinds of html controls are automatically rendered by writing the corresponding easyui style. See the class = "easyui-dialog" data-options in the pop-up layer. = "closed: true, title: 'New student registration', modal: true"

In fact, it is very easy to understand the literal meaning of thias. These parameters are included in the easyui document. You can also write data-options on the html element for verification ,:

<Div id = "addBox" class = "easyui-dialog" data-options = "closed: true, title: 'New student registration', modal: true" style = "width: px; height: px "> <table class =" auto-style "> <tr> <td> Student name: </td> <input id = "stuname" class = "easyui-textbox" data-options = "required: true, missingMessage: 'required! ', ValidType: 'email', invalidMessage: 'incorrect email format! '"Type =" text "/> </td> </tr> <td> class: </td> <input class = "easyui-combobox" id = "grad" name = "grad" data-options = "valueField: 'id', textField: 'gradname', required: true, missingMessage: 'required! '"/> </Td> </tr> <td> <input id =" saveBtn "onclick =" saveClick () "type =" button "value =" save "/> </td> <input id =" Button "type =" button "onclick =" $ ('# addBox '). dialog ('close'); "value =" close "/> </td> </tr> </table> </div>

Create button:

Copy codeThe Code is as follows:
<A id = "Button1" onclick = "$ ('# addbox'). dialog ('open');" class = "easyui-linkbutton"> New </a>

Do not use the button element. This is the <button> newly added </button>.

Save the js function called by the button:

// Save information function saveClick () {var isvaliok = $ ("# addBox "). form ('validate'); // id of the div box whose information needs to be submitted in the package if (isvaliok = false) {$. messager. show ({title: 'hprompt ', msg:' Please complete the incorrect items before submitting ', showType: 'show'}); return ;} var stu = {}; stu. name = $ ("# stuname "). val (); stu. age =; stu. gradId = $ ("# grad "). combobox ('getvalue'); stu. gradName = $ ("# grad "). combobox ('getvalue'); if (isNaN (stu. gradId) stu. gradId = null; var rst = WebApplication. newFolder. helloAjaxNet. addStu (stu); if (rst. value = "OK") {$ ('# addbox '). dialog ('close'); $ ('# studb '). datagrid ('reload'); var gradData = WebApplication. newFolder. helloAjaxNet. getGrad (). value; $ ('# grad '). combobox ({data: gradData }). combobox ('reload');} else {$. messager. show ({title: 'hprompt ', msg: rst. error. message + rst. value, showType: 'show '});}}


Var isvaliok = $ ("# addBox "). form ('validate'); // id of the div box whose information needs to be submitted in the package if (isvaliok = false) {$. messager. show ({title: 'hprompt ', msg:' Please complete the incorrect items before submitting ', showType: 'show'}); return ;}

Verification in easyui is simple. As long as the authentication format is defined in html code, you only need to input the id $ ("# addBox") of the outermost container control "). form ('validate') will automatically help us verify. In addition, the UI also prompts that the focus is automatically placed on the control that fails the first verification. We do not need to do it.

Of course, when we use document. ready () on the client, we must bind the table and the data in the drop-down box:

$ (Function () {// page initialization // load table data bindDataToTb (); // load the class drop-down box var gradData = WebApplication. newFolder. helloAjaxNet. getGrad (). value; $ ('# grad '). combobox ({data: gradData }). combobox ('reload'); var fd = new FormData ();});

Code saved by the server:

// Add [AjaxPro. ajaxMethod] public string addStu (StudentsInfo stu) {MyDb db = new MyDb (); if (stu. gradId = null) {if (string. isNullOrEmpty (stu. gradName) = false) {Grad grd = new Grad (); grd. gradName = stu. gradName; Grad grdOld = db. grads. firstOrDefault (r => r. gradName = stu. gradName); if (grdOld! = Null) {return "category already exists";} else {db. grads. add (grd); stu. grad = grd ;}} db. students. add (stu); db. saveChanges (); return "OK ";}

If the server code does not have this id category, we think this category is new. Add a new category and immediately bind it to perfect. It's great.


Does it look like a pattern. Management Software is okay.

In this way, the ui is like that. When you need to customize the style, you will find that all the UIS are cloud-based. For example, I have already made many UIS by writing js in China, the table is very beautiful and powerful. In fact, you still can't use many functions. It's still very difficult for you to change it. Of course, my js is also very delicious. You need to familiarize yourself with another set of UIS. I just want to use a simple custom paging table or a server control like's repeat streaming layout for four rows of data. Do it yourself. Php contains a front-end template.

Here I just want to know the power of angular from the actual needs. In php, templates and other things are built on cloud float to create a webform HelloAjaxNetAngular. aspx.

Note that in this example, all the server code I use will not change at all, but the front end will change. The main idea of angularjs is that the mvvm mode is the dynamic binding of dependency attributes in wpf, I don't know if you have used it or not. I feel like it is a good word. It is a waste to make this database platform program mfc winform.

I will not discuss the basics of angularjs, but I will directly start with the requirement to create a paging table and information update function.

Angularjs site is site in China is also not accessible. Some of the study notes related to others have

Anyway, I have read these two tutorials, but I have nothing to do with it. I feel like I am chewing wood. Although angularjs's philosophy is mvvm, angularjs itself still feels obscure.

I wrote this example in a semi-understandable state. Almost all operations do not need to change the dom like jquery. I really feel his strength. The front-end is a controller function that manages the entire page. I don't know how to manage the entire page one by one. I just know that the controller and html have the same tree structure. Html elements that are not in the range cannot access the variables in their controller.

Let's take a look at this controller function. I don't feel anything when I write it. It just feels like two things exist. The business logic is operating data. Like the code for writing c # data operations:

Function myCtr ($ scope) {var mod = [{name: 'xiang ', age :}, {name: 'xiang', age :}, {name: 'xiang ', age:}]; $ scope. data = mod; $ scope. curobj ={}; $ scope. pageEntity = {total:, rows:, page:, pgmsg: ''} // initialize the default first page $ scope. initPage = function () {var firstPage = WebApplication. newFolder. helloAjaxNetAngular. bindData ($ ("# txtkeyword "). val (), $ scope. pageEntity. page, $ scope. pageEntity. rows); $ scop E. data = firstPage. value. rows; var pageEntityMod ={}; pageEntityMod. total = firstPage. value. total; pageEntityMod. rows = $ scope. pageEntity. rows; pageEntityMod. page = $ scope. pageEntity. page; var totalpage = pageEntityMod. total % pageEntityMod. rows =? ParseInt (pageEntityMod. total/pageEntityMod. rows): parseInt (pageEntityMod. total/pageEntityMod. rows) +; pageEntityMod. pgmsg = "Total" + pageEntityMod. total + "records per page" + pageEntityMod. rows + "entries, total" + totalpage + "Page, current" + pageEntityMod. page + "page"; $ scope. pageEntity = pageEntityMod; $ scope. curobj ={};}// update the currently selected $ scope. modifyCur = function () {var rst = WebApplication. newFolder. helloAjaxNetA Ngular. updateStu ($ scope. curobj) // refresh the selected information in the table and restore $ scope. initPage (); alert (rst. value);} // click $ scope. nextPage = function () {var totalpage = $ scope. pageEntity. total % $ scope. pageEntity. rows =? ParseInt ($ scope. pageEntity. total/$ scope. pageEntity. rows): parseInt ($ scope. pageEntity. total/$ scope. pageEntity. rows) +; var pagenewnum = $ scope. pageEntity. page +; if (pagenewnum <= totalpage) $ scope. pageEntity. page + =; $ scope. initPage ();} // page flip $ scope. previousPage = function () {var pagenewnum = $ scope. pageEntity. page-; if (pagenewnum >=) $ scope. pageEntity. page-=; $ scope. initPage ();} // search for $ scope. search = function () {}// select a $ scope row. del = function (sender, curobj) {// restore the color of all rows // set the color of the selected row var rows = rows (sender.tar get ). parent (). parent (). parent (). find ("tbody "). find ("tr"); for (var I =; I <rows. length; I ++) {detail (rows[ I ]).css ("background", "white");} explain ( ("background", "# ffed"); $ scope. curobj = curobj;} // first call to obtain the first page $ scope. initPage ();}

Interface section:

<Div ng-controller = "myCtr" id = "mygrid"> <input id = "txtkeyword" type = "text"/> <input ng-click = "initPage () "type =" button "value =" Search "/> <br/> <div style =" height: px "> <table cellspacing =" "border =" "class =" gridtable "> <thead> <th width =" px "> name </th> <th width =" px "> age </th> </thead> <tbody ng-repeat =" stu in data "> <tr ng-click = 'del ($ event, stu) 'style = "background-color: white"> <td >{{ stu. name }}</td> <td >{{ stu. age }}</td> </tr> </tbody> </table> </div> <div id = "pager"> <a href = "#" ng- click = "previousPage () "> previous page </a> <a href =" # "ng-click =" nextPage () "> next page </a> <span >{{ pageEntity. pgmsg }</span> </div> <div> name: <input type = "text" value = "{curobj. name }}" ng-model = "curobj. name "/> <br/> Age: <input type =" text "value =" {curobj. age }}" ng-model = "curobj. age "/> <input id =" Button "type =" button "ng-click =" modifyCur () "value =" change "/> </div>

I have built a data binding function. See the datagrid loader in easyui. After obtaining the paging information for the first request, I immediately bound the data to the table. You can see that it is exactly like a template, and then initialize your own paging control. In ng-click mode, the client click is triggered as before and the method in controller is called to update data. Note that you only need to update data based on the business logic. It takes less than 10 minutes to get started with angularjs and bind data if you do not understand the above two sections of code,

Because of the two-way binding mechanism of wpf, the data model data updates the page content and automatically changes. You can even see that when I edit the data in the text box below, the data in the above table has not been submitted, and the change is because their data comes from the same place, it seems like ajax.


The source code of all the examples above can be directly downloaded and run, because some external libraries are introduced in 10 MB, it almost cannot be placed


As a matter of fact, if the Internet promotes development like this, the front-end will unify the front-end. At that time, a webpage will be a system and a client. The backend is only responsible for data and security. Currently, html5 is almost an industrial standard, and some embedded devices support it.

For the time being, I have seen a few articles on the mvc mode of frontend and backend operations of the same model. The attributes are updated automatically to the backend and persisted to the database. or the value of the front-end html page of an attribute of the backend model is automatically changed. I don't mean I can't do it. After all, there are so many cool people. I think it is at least not stable.

Various UIS include easyui ligerui fineui miniui Devexpress. There are also many js frameworks seajs requirejs JavaScriptMVC backbone avalonjs knockout angular jquery jqueryui js. This is really the same thing. You can't finish learning all kinds of frameworks.

In particular, the software industry is changing with each passing day. There are too many frameworks and platforms based technologies. If you are not proficient in a certain technology, you can use it, however, as a technician, you must be at least proficient in the same or one technology. Otherwise, it would be a great pity that I am still working on the road. Writing business code is a mix of ten years of experience, and writing business code is the essence of his work, as long as a good programmer has been working on such a database system for a long time, he will be able to quickly develop the so-called small framework and accumulate some of his own tool libraries and experience.

Do not be biased at work. As long as he writes business code out every day, software development is just a profession. You are not a hero, and the goal is to solve the problem is not a cool.

I personally don't have a bad idea about js. the imperfect design at the beginning has caused various obstacles for us to use it, but you have to use it for web development. This is not a prejudice against the front-end. thanks to those who have thoroughly eaten the front-end, the masters of situ zhengmei have created these tools to make it easier for us to complete these website programs.

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: 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.