0

大家好,当且仅当搜索文本框值不同于默认值时,我想将参数附加到 url。实际上我有 3 个搜索文本框,我想将它们附加到 url

这是我的代码..

$("#search-btn").click(function (e) {
    e.preventDefault();
    var search_country = $("#search-country").val();
    var search_city = $("#search-city").val();
    var search_team = $("#search-team").val();
    var dataString = 'action=search'

    // var dataString = {
    //   action : 'search',
    //   param1 : $("#search-country").val() || '', 
    //   param2 : $("#search-city").val() || '',
    //   param3 : $("#search-team").val() || ''
    // };

    if (search_country != "Search by Country") {
        dataString = dataString + "&param1=" + search_country
    }
    if (search_city != "Search by City") {
        dataString = dataString + "&param2=" + search_city
    }
    if (search_team != "Search by team") {
        dataString = dataString + "&param3=" + search_team
    }
    $.ajax({
        type: "get",
        url: "SearchServlet",
        data: dataString,
        success: function (data) {
            $('body').html(data);
            $('#msg').html('Search Results')
        }
    });

});

我只想在用户输入搜索条件时才传递参数,否则不......

4

2 回答 2

2

尝试这个:

$("#search-btn").click(function (e) {
    e.preventDefault();
    var search_country = $("#search-country").val();
    var search_city = $("#search-city").val();
    var search_team = $("#search-team").val();
    var dataString =  {};

    dataString["action"] = "search";

    if (search_country != "Search by Country") {
        dataString["param1"] = search_country;
    }
    if (search_city != "Search by City") {
        dataString["param2"] = search_city;
    }
    if (search_team != "Search by team") {
        dataString["param3"] = search_team;
    }
    $.ajax({
        type: "get",
        url: "SearchServlet",
        data: dataString,
        success: function (data) {
            $('body').html(data);
            $('#msg').html('Search Results')
        }
    });

});
于 2013-09-26T16:36:43.390 回答
2

最后我记得,jQuery 将获取一个 JavaScript 参数对象并将其转换为 GET queryString 参数。只需准备您的对象

$("#search-btn").click(function (e) {
  e.preventDefault();
  var search_country = $("#search-country").val();
  var search_city = $("#search-city").val();
  var search_team = $("#search-team").val();

  var params = {
    action : 'search'
  };

  if (search_country != "Search by Country") {
    params.param1 = search_country
  }
  if (search_city != "Search by City") {
    params.param2 = search_city
  }
  if (search_team != "Search by team") {
    params.param2 = search_team
   }
  $.ajax({
    type: "get",
    url: "SearchServlet",
    data: params,
    success: function (data) {
        $('body').html(data);
        $('#msg').html('Search Results')
    }
  });

});
于 2013-09-26T16:37:40.673 回答