Use ajax to achieve partial page refresh

  

  Briefly

  The function of partial page refresh has been common on web sites, such as real-time news information, stock information, etc., all need to continuously obtain the latest information. In the traditional web implementation, to achieve a similar effect, the entire page must be refreshed. Under the circumstance that the network speed is limited to a certain extent, this processing method that affects the entire page due to a local change seems to be a bit of a loss. The emergence of Ajax technology solves this problem very well. Using Ajax technology can realize partial refresh of web pages, only update the specified data, and not update other data. This article uses a login case to introduce the use of ajax.

  login html key code

  body

  账号:input type=text name=username

  密码:input type=text name=password

  button id=btn_login login/button

  /body

  Analysis: In traditional projects, to submit form data to the background, we all use form forms. At this time, using ajax technology, we will abandon the previous form submission methods.

  ajax key code

  script type=text/javascript

  $(#btn_login).click(function() {

  $.ajax({

  url : login.do,

  type : post,

  data : {

  username : $(input[name=username]).val(),

  password : $(input[name=password]).val()

  },

  dataType : json,

  success : function(result) {

  var flag = result.flag;

  if (flag == true) {

  alert(password is correct!);

  } else {

  alert(wrong password!);

  }

  }

  });

  });

  /script

  Analysis: To use ajax technology, we need to rely on jQuery, so we need to introduce the jQuery package when using ajax

  ajax syntax features

  url: request address

  type:传递方式(get/post)

  data:用来传递的数据

  success:交互成功后要执行的方法

  dataType:ajax接收后台数据的类型

  servlet关键代码

  protected void doPost(HttpServletRequest req, HttpServletResponse resp)

  throws ServletException, IOException {

  //获取用户名和密码

  String username = req.getParameter(username);

  String password = req.getParameter(password);

  //创建json对象

  JSONObject jsonObject = null;

  if (root.equals(username) 123456.equals(password)) {

  jsonObject = new JSONObject({flag:true});

  } else {

  jsonObject = new JSONObject({flag:false});

  }

  //将数据返回给ajax

  resp.getOutputStream().write(jsonObject.toString().getBytes(utf-8));

  }

  解析:如图我们将用户名设置为 root ,密码设置为123456,如果用户输入的跟设置的一致将提示密码正确,否则提示密码错误!

  


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325167992&siteId=291194637