Cascading operation of ajax drop-down menu

小云云
Release: 2023-03-19 13:18:02
Original
1274 people have browsed it

In development, we often encounter menu cascading operations, such as: selection of countries, cities, towns, etc. When a country is selected, the following menu will list the cities in that country. When a city is selected, the following menu will list the corresponding towns. This article mainly introduces the cascade operation of the drop-down menu in detail, and shares the tool class for interactive transmission of data between ajax and the background. Interested friends can refer to it. I hope it can help you.

There are two ways I understand to solve the cascading operation of this kind of menu:

①Use js to implement, put the cascading data used on the page into js, ​​when After the page is loaded, it is displayed in the corresponding select through js. There are many solutions to this method. The most intuitive one is to put it into a multi-dimensional array. Everyone has different thinking, so I will not explain it in detail here.

② Use ajax to load asynchronously and dynamically, and then display it in the corresponding select. This method is very convenient and is recommended for use in development.

Let’s look at a small example in development:

JSP short page:

      <p class="form-group">
        <label class="col-sm-2 control-label">设备类别</label>
        <p class="col-sm-4">
          <select class="basic-single" name="codeCategory" onchange="showCodeSubCate()" id="codeCategory" style="width: 100%">
          
          </select>
        </p>
        <label class="col-sm-2 control-label">设备子类</label>
        <p class="col-sm-4">
          <select class="basic-single" name="codeSubCategory" id="codeSubCate" disabled="disabled" style="width: 100%">
            <option value="">--请选择--</option>
          </select>
        </p>
</p>
Copy after login

This page involves two options: device classification and device subcategory. The device classification is the first-level menu, and the device subcategory is the second-level menu. The display content of the device subcategory is determined by the device classification.

Let’s look at the ajax code snippet:

function addCodeCategory(){
    $.ajax({
      url: "<%=request.getContextPath()%>/facilitydict/showCodeCategory",
      async: false, //请求是否异步,默认为异步,这也是ajax重要特性
      type: "GET",  //请求方式
      success: function(result) {
        result = $.parseJSON(result);
        var data = result.data;
        var codeCates = data.split(",");
        str =&#39;<option value="6801">--请选择--</option>&#39;;
        for(x in codeCates){
          str+=&#39;<option value="&#39;+codeCates[x]+&#39;">&#39;+codeCates[x]+&#39;</option>&#39;;
        }
        $("#codeCategory").html(str);
        
      }
    });
  }
  
  function showCodeSubCate(){
    $("#codeSubCate").prop("disabled","");//将设备子类的select解除锁定
    var target = $("#codeCategory option:selected").text();
    $.ajax({
      url: "<%=request.getContextPath()%>/facilitydict/showCodeSubCategory",
      data : {codeCategory:target},
      async: false, //请求是否异步,默认为异步,这也是ajax重要特性
      type: "GET",  //请求方式
      success: function(result) {
        result = $.parseJSON(result);
        var data = result.data;
        var codeCates = data.split(",");
        var str="";
        for(x in codeCates){
          str+=&#39;<option value="&#39;+codeCates[x]+&#39;">&#39;+codeCates[x]+&#39;</option>&#39;;
        }
        $("#codeSubCate").html(str);
      }
    });
  }
Copy after login

It is not difficult to see that when the content in the device category selector After the change occurs, the showCodeSubCate function is triggered to request the background to obtain data, and then the requested data is added to the select corresponding to the device subclass. The implementation of the background code is as follows (only the controller methods are posted):

@RequestMapping("/showCodeCategory")
  @ResponseBody
  public Result<String> searchCodeCategory() {

    Result<String> rs = new Result<>();
    List<String> codeCategorys = facilityDictService.searchCodeCategory();
    String codeCate = StringUtil.collectionToCommaDelimitedString(codeCategorys);
    rs.setData(codeCate);
    return rs;

  }

  @RequestMapping("/showCodeSubCategory")
  @ResponseBody
  public Result<String> searchCodeSubCategory(HttpServletRequest request) {
    String codeCategory = request.getParameter("codeCategory");
    Result<String> rs = new Result<>();
    List<String> codeSubCategorys = facilityDictService.searchCodeSubCategory(codeCategory);
    String codeCate = StringUtil.collectionToCommaDelimitedString(codeSubCategorys);
    rs.setData(codeCate);
    return rs;
  }
Copy after login

These two methods respectively correspond to the two ajax requests above, which is worth What is introduced is the data returned by the background. The return value type is Result. The return value type is a tool class. The specific implementation can be viewed in my blog. The link is: http://www.cnblogs.com/blog411032 /p/5799669.html

Ajax tool class for interacting with the background to transmit data

 public class Result<T> implements Serializable {

  private static final long serialVersionUID = 3637122497350396679L;

  private boolean success;
  private T data;
  private String msg;

  public Result() {
  }

  public Result(boolean success) {
    this.success = success;
  }

  public boolean isSuccess() {
    return success;
  }

  public void setSuccess(boolean success) {
    this.success = success;
  }

  public T getData() {
    return data;
  }

  public void setData(T data) {
    this.data = data;
  }

  public String getMsg() {
    return msg;
  }

  public void setMsg(String msg) {
    this.msg = msg;
  }

  public Result(boolean success, String msg) {
    super();
    this.success = success;
    this.msg = msg;
  }

  public Result(boolean success, T data) {
    super();
    this.success = success;
    this.data = data;
  }

}
Copy after login

This class provides a very large platform for front-end and back-end interaction Convenience:

The following is the ajax interaction between the front and backend:

The front-end ajax code:

$.ajax({
      url: "<%=request.getContextPath()%>/supp/deleteSupp",
      data : {supplierId:supplierId},
      async: false, //请求是否异步,默认为异步,这也是ajax重要特性
      type: "GET",  //请求方式
      success: function(data) {
        var rs = eval(&#39;(&#39;+data+&#39;)&#39;);
        flag = rs.success;
        if(flag){
          alert("删除成功!");
        }
      }
    });
Copy after login

The following is the background java code:

  @RequestMapping("/deleteSupp")
  @ResponseBody
  public Result<String> deleteSupplier(HttpServletRequest request){
    Result<String> rs = new Result<>();
    String supplierId = request.getParameter("supplierId");
    supplierService.deleteSupplierById(supplierId);
    rs.setSuccess(true);
    return rs;
  }
Copy after login

Related recommendations:

Pure CSS Tutorial on how to implement a drop-down menu

JQuery implementation of a drop-down menu method sharing

jQuery implementation of the accordion effect of a drop-down menu

The above is the detailed content of Cascading operation of ajax drop-down menu. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
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!