Home > Web Front-end > JS Tutorial > body text

Solutions to several problems in html ashx development_jquery

WBOY
Release: 2016-05-16 18:04:42
Original
1077 people have browsed it

Question 1: Use delegate dictionary instead of switch...case.

This problem was discovered when processing requests. Everyone is definitely not willing to build many handlers in their own projects to handle so many requests, so they thought of handling multiple requests in one handler, ajax An action parameter is added to the request, and the handler performs corresponding processing or returns corresponding data based on this action. No one here uses if...else to judge the action. Most people will think of using switch...case , I also used switch at the beginning, but gradually I discovered that each case is not like a code block and cannot provide an independent scope for the variables in it! In the words of Sun Wukong from Dragon Ball, "It's really nerve-wracking."

I searched online and found that many people have encountered this problem. One solution is to separate each process into a method in the handler, which is clear and concise, but in the ProcessRequest method, you must use reflection to call the corresponding method! I was not very satisfied with this solution, so I thought of delegation and dictionary, and turned the reflection calling method into indexing the delegate in the dictionary.

First declare a private static delegate dictionary in handler:

static Dictionary> hs;
Then use handler (general handler class) Initialize hs in the static constructor, and more importantly, add the processing method in the static constructor:

Copy the code The code is as follows:

static Handler()
 {
hs = new Dictionary>();
hs.Add("add", delegate()
  {
  int id = int.Parse(req("id"));
  string title = req("title");
   return "add";
  });
hs.Add("update", delegate()
int id = int.Parse(req("id")); string title = req("title");
   return "update"; Code


The code is as follows:

context.Response.ContentType = "text/plain";
HttpRequest req = context.Request;
string action = req["action"].ToLower();

Copy code


The code is as follows:

static string req(string key)
{
return HttpContext.Current.Request[key];
Problem 2: Permission issue.

You definitely don’t want your data to continue to be accessed when the user is not logged in or the login has expired. It is assumed here that the logged-in user is stored in Session["user"]. Of course, it is very simple to judge Session["user"] in the handler, but the problem is how do you make the user when Session["user"] is null? Jump to the specified page (assumed here is the login page login.html). Haha, at this time, would you think of using context.Response.Redirect ("login.html") to solve it? My first reaction is this, but after analysis, ajax requests data. This is done by letting ajax request the login.html page. The result should be the source code of login.html. The analysis is as follows Yes, but I still didn’t give up and tested it. As analyzed, the source code of login.html was returned as the ajax request result!

In fact, everyone understands that there is a very simple method, which is to return a specific value when Session["user"] is null. Here we assume "unlogin", and then judge after each ajax request is completed. The return value is "unlogin".

This method is very simple and reliable, but it is clumsy, troublesome and not very feasible. So I thought of jquery.ajaxSuccess() again and wanted to use it for unified processing. When I thought of it, I was a little worried whether jquery would first call the callback function of the specific request and then call the global callback. What about functions? I did a test with this question, and the result was as expected. The callback for the specific request was executed first and then the global callback was executed! I had no choice but to check the source code of jquery~. I found the success() method in the uncompressed jquery-1.4.2.js, and sure enough, after changing the order, it is as follows:
Copy code The code is as follows:

function success() {
if ( s.global ) {
trigger( "ajaxSuccess", [xhr, s] );
}
   // If a local callback was specified, fire it and pass it the data
  if ( s.success && xhr.responseText!="unlogin" ) {
   s.success.call( callbackContext, data, status, xhr );
  }
 }

  The execution order has been changed. Where should I write the jumpable code? Write it once for each page? No, no, this is not our style of writing programs. After thinking about it, writing it into the jquery file (at the bottom) is a feasible method:
Copy code The code is as follows:

$(document).ajaxSuccess(function(event,xhr,settings){
if(xhr.responseText=="unlogin"){
window.top.location.href="/login.html";
}
})

It is very clear that not every ajax request on the page requires the user to log in , such as the login.html page, so the pages that do not need to be logged in should be excluded when judging:
Copy the code The code is as follows:

 if (HttpContext.Current.Request.UrlReferrer.ToString().ToLower().IndexOf("login.html") < 0)
 {
 if (HttpContext.Current.Session[ "user"] == null)
  {
   HttpContext.Current.Response.Write("unlogin");
   HttpContext.Current.Response.End(); 🎜>

Question 3: Data template.
Whatever is needed, everything comes into being! Before writing this essay, I happened to see an article about jquery.tmpl in the garden! The creation of tmpl is exactly the solution to this problem! I know that this method is not as powerful as tmpl, but there is a problem with tmpl that has not been solved. In fact, there are two main problems with templates. 1. It is difficult to edit if the template is stored in js, and 2. Where should the template be stored to facilitate design? time view! tmpl stores the template in the tag. It should be said that it solves the first problem, but I feel that the second problem is also very important. ! After much deliberation, I can only store the template directly in the container tag of the data:



  • {Title}< br />
    {Content}




  • Write the template directly in the target container, just like a piece of data. It is not a problem for the artist to adjust the style, and it is not a problem for the program to add methods. I think this method will work! But js will definitely not directly operate this template. What we need to do now is to turn this template into a real template:
    Copy code The code is as follows:

    $(function() {
    var ulList = $("#ulList");
    ulList.data("tpl",ulList.html()) .empty();
     }

    It should be most appropriate to store the template in the data of the container, and do this immediately after the page is loaded! Then empty the container and let it go! The background provides json data for the real data loaded later. This is very simple:
    Copy code The code is as follows:

    public class News
    {
    public int ID { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }
    }
    //The solution to the first problem above is used in handler
    hs.Add("getNews", delegate()
     {
    List list = new List< News>()
      {
       new News(){ ID=1,Title="title1",Content="Content1"},
    ,Content="Content2"},
      new News(){ ID=3,Title="title3",Content="Content3"},
      };
     return jss(list);
    });

    There is nothing to say about getting data at the front desk, this is very basic:
    Copy code Code As follows:

    $.get("Handler.ashx?n=" Math.random(), { action: "getNews" }, function(data) {
    var list = $. parseJSON(data);
    var ul = $("#ulList");
    var html = "";
    for (var i = 0; i < list.length; i ) {
    html = ul.data("tpl").format(list[i]);
    }
    ul.html(html);
    })

    The string.format method was used when generating data. It is recorded in the string.format essay in my js. Haha, I didn’t expect this. When I wrote the format, it was just for the purpose of making it support json objects. Easy to read, yet so appropriate to use! By the time I got here, I was very excited. The test results are as follows:

    But after I added events, I found it wasn’t good enough. If onclick="show({ID},'{Title}')" is added to the template li, there will be a js error when the page is first opened in IE. Why is this? The problem lies in the ID parameter, because {ID} is regarded as a json object, but it is a json with an incorrect format! The js error prompt is also normal. There is no error in '{Title}' because it is regarded as a string parameter. . Although this js error does not affect the program, no one likes the code they write without js errors! The solution is very simple, just add quotation marks like the Title parameter. If you really need a numeric type in the show method, you have to convert it there! But you will definitely find that many times there is no need to convert, and you even want it to be a string type!

    I have never written an essay so seriously. I took this afternoon off in three weeks. I didn’t accompany my girlfriend, sleep, or go out to drink with friends, but I finished it honestly!
    Related labels:
    source:php.cn
    Previous article:javascript image zoom function implementation code_image special effects Next article:JS custom function with default value_javascript skills
    Statement of this Website
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
    Latest Articles by Author
    Latest Issues
    Related Topics
    More>
    Popular Recommendations
    Popular Tutorials
    More>
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!