用户输入在AJAX URL调用中未正确反映

时间:2017-11-14 00:00:29

标签: javascript jquery ajax

尝试使用用户的城市输入(例如洛杉矶)并包含在Ajax网址参数中,但是当我console.log(searchURL)时。它不会在'+'之间添加"los angels",从而破坏了网址。如何使URL包含两个单词的城市之间的+

var apiKey = "&client_id=OTU3MDMwMHwxNTEwMjUwNDQ0LjI3"
var baseQueryURL = "https://api.seatgeek.com/2/events?" + apiKey;
console.log(baseQueryURL);

function runSearch(queryURL) {
  $.ajax({
      url: queryURL,
      method: 'GET'
    }).done(function(response) {
        console.log(response);
      };

      $("#submitSearch").on("click", function(event) {
        //prevents default event from occuring
        event.preventDefault();

        userCity = $("#userCity").val();
        console.log(userCity);
        //create variable queryCity to hold city queried with URL parameters
        var queryCity = "&venue.city=" + userCity;
        //create searchURL to pass in as queryURL in AJAX call
        searchURL = searchURL + queryCity;
        console.log(searchURL);
        runSearch(searchURL);
      });

2 个答案:

答案 0 :(得分:1)

URL-encode价值:

userCity = encodeURIComponent($("#userCity").val());

答案 1 :(得分:-1)

我用过这个:

userCity.split(" ").join("+")