Background
In a new project being developed by our department, we chose jQuery as the basic Javascript function library. The ajax methods provided by jQuery are also determined as the basic interface for asynchronous push-pull data.
Colleagues who have used ajax methods should know That ajax methods need to provide a set of selection options, such as content-type, mime-type, data, and async, the combination of these options can constitute different request methods. You must understand part of the HTTP protocol to complete the configuration correctly. Of course, you can also find the configured code snippet copy from google to use it. The defects of this method will not be mentioned much.
My mistakes
1. You have not specified how to use jQuery's ajax method before writing the code. As a result, developers directly write the ajax method call in the script block of the page, causing the following code to appear in the page:
$. Ajax ({type: "post", contentType: "application/json", datatype: "json", async: false, url: "DemoHandler. asmx/GetData ", data:" {index: 1} ", complete: function (e, s) {alert (" OK ")});
Analysis Phenomenon
The above code is intended to call the GetData method of web services on the server through the http post method. The input parameter name is index and the value is 1. This is an encoding method with a strong coupling relationship between the hard encoding method and the server, which implies the following problems:
1. If the path of the DemoHandler. asmx file is changed, all such code on the page will be affected;
2. If the method signature of GetData on the server changes, all such code on the page will be affected;
3. If there is a better ajax framework in the future, the workload of replacement will also be retried;
4. If a method like GetData is called elsewhere, the method used is to copy such code;
5. When we advocate separate development at the front and back ends, theoretically, front-end developers should be proficient in technologies such as div + css and js, so that back-end developers should focus on technologies such as web services. Only in this way can we refine and optimize our respective fields. The first template of the code shown above is provided by me, because I personally assume the role of a bridge between the UNICOM frontend and backend technology, but I think that he is a personal act, but not the embodiment of Team strength.
6. developers can ask themselves, what is the role of the contentType: "application/json" option? Why can DemoHandler. asmx/GetData be successfully transferred to the web services method? Why is data written as "{index: 1? I tried to ask the project team, but the answer was unknown. Obviously, development is only related to the business, rather than the knowledge of these underlying protocols. It can block everyone.
Solution
When you have analyzed the existing problems clearly, the answer will be given. We write a specialized js file for each web serivices, which encapsulates a set of functions with the same signature as the web method. In this way, the page can be called only by passing parameters through the js method, instead of paying attention to the details of the ajax call options. Developers with different responsibilities pay attention to the requirements of different functions.
There was another episode in the execution of this incident. Those responsible for writing js files refer to the js Writing Style of other online cool people and are also playing popular JavaScript tricks-dynamic objects and closures. Of course, it will soon be rejected. There are not many other reasons, but there is only one reason to note: any programming skills and technology should be used to consider whether it is suitable for the general level of the team, if not, consider other methods. Closure is obviously just a trick, not a solution. The introduction of this function increases the difficulty of reading code by at least the average person, so it must be passed.
Finally, we chose to use a prototype in the vernacular to declare the service object. At the beginning, I wrote an initialization function in the header, which encapsulates all the option configuration information and extends the service object to the jQuery system, this allows developers to call server functions according to the same specifications. Later, other developers only need to append the functions corresponding to the server method at the end of the file as needed.
Optimization and Improvement
In order to use. net script services to expand web services, the project team initially required that web services be directly provided in the background to expose the client. This is no problem for the client to submit data, but it is not suitable for some of the controls we use. Because the control requires that the returned value be a pure json data, and the script services framework will package a d root on the outer layer of the output json data, the control cannot identify the data source. The project team uses the ashx file to implement Ihttphandler to manually process requests.
Soon, more than 10 ashx files were added to the server project because the client needed more than 10 different data requests. Each ashx internal ProcessRequest method handles four major events: 1) Setting HTTP header information for WEB feedback; 2) processing business logic; 3) serializing business data to JSON; 4) write JSON data to the output stream.
This phenomenon illustrates two problems: 1) the number of ashx files will increase with the increase of application requirements, which will be difficult to maintain in the future; 2) only one of the four things must be done every time, that is, to process the business logic. Other events are regular and repetitive.
Based on the above problems, the project team has made improvements to implement a unified Web Request Scheduling and processing mechanism, so that the same type of requests can be placed in an ashx file, in addition, each request is directly mapped to a function, and the output, output, and cache are handled by this mechanism. In addition, common developers only need to complete the business logic code, do not care about anything else.
After another two days, I was troubled by new problems. If the server adds a new method, the client js also needs to add a function that matches it as the call proxy. In this way, the same semantic function generates two maintenance points in the front and back of the system, which is unreasonable. It is also a mechanical task, and every time it is developed and manually done, it is also non-human. Therefore, the new solution is that when the client directly requests the ashx file, the server automatically generates the corresponding client proxy script. This makes the client code more improved. We only need to place <SCRIPT src = ".. \ xhandler. ashx"> into the page, and everything is OK. Because the automatically obtained JS script will automatically initialize the client service, and the service can be called anywhere on the page in the future through such a method: $. net. xhandler. getdata ()
After this improvement, the developers of the project team are full of joy, because they can do less unnecessary things, write code more cleanly, and reduce bugs. Since then, we have solidified the technical solutions that integrate jquery. Ajax and. net. In the future, the team will rely on the stable technical work, instead of the individual. By the way, when writing the code, we have considered frameworks such as ajaxpro.net and. Net MVC, but they are not suitable for us.
Finally, the source code is included: WebHandler.zip.
A friend asked: Why don't you use ajaxpro? I have a very simple reason, because I have enough strength to manage my current needs. When I find that 1000 lines of code can meet the requirements, I will not introduce a set of DLL, not to mention I need to learn it. After completing the module mentioned in this article, I spent only one afternoon and one night. I stick to the idea that we should not move the entire dyeing tank out of color.
On November 5.27, A friend asked a question: if. ashx contains n methods, but the front end only needs one or several of them. In this case, the client will generate JS containing all methods. How can this problem be solved? There are three answers:
1. When the script references the block script src attribute reference. ashx, you can add a parameter later, such as src = xHandler. ashx? Find = method & like = get *, modify the GetSvr method synchronously, and set its signature to public StringBuilder GetSvr (string find, sting like) to obtain parameters sent from the client, find indicates the matching method, such as name matching and like indicates the matching mode. For example, if all methods starting with get are modified, I will not elaborate on the internal logic of the function.
2. this problem is avoided in my actual project because I only use one Master page for the entire project. Although different pages are separated during development, these pages are obtained asynchronously as web parts and embedded in the pseudo windows (div implementation) of the Master node ). Therefore, pages that serve as web parts do not actually need to reference. ashx. It directly shares the scripts already loaded on the Master page.
3 .. ashx can directly load and generate a script file through a browser. We can manually download this file, crop the required method, and add it to the project manually without reference in the script. ashx. This is also the reason why every. ashx script file is templated, single-layer, because it makes it easier for developers to modify the template themselves, without relying on other. This is also one of the potential best practices for this project.