当且仅当javascript中存在文本框值时,如何将参数附加到查询字符串?

时间:2013-09-26 16:30:32

标签: javascript jquery ajax servlets

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

这是我的代码..

$("#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')
        }
    });

});

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

2 个答案:

答案 0 :(得分: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')
        }
    });

});

答案 1 :(得分: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')
    }
  });

});