如何在函数中传递没有引号的字符串作为参数?

时间:2016-04-03 12:12:42

标签: javascript ajax reactjs tastypie

如果我的api将查询作为http://localhost:8000/api/v1/rental/?place__startswith=kathmandu,那么我如何在reactjs中进行通用搜索。我尝试的是我将默认参数作为搜索(query = kathmandu)传递,以便默认列出名为kathmandu的地方的结果,当用户键入他们想要搜索的地名时,它应该显示那些地方而不是kathmndu。但我得到一个错误说未捕获的ReferenceError:没有定义加德满都。我该如何解决这个问题?

componentWillMount(){
        this.search();
      }

search(query=kathmandu){
    let url = 'http://localhost:8000/api/v1/rental/?place__startswith=query';
    Request.get(url).then((response) => {
        console.log('response',response.body.objects);
        this.setState({
            place:response.body.objects
        });
    });
  }

  searchUpdated(term){
    console.log('term is',term);
    this.search(term);
  }

  render() {
        var margin = { marginTop : '13em' }; 
        let location = _.map(this.state.place, (place) => {
            return(
                    <div className="searchResult">
                        <li>{place.place}</li>
                        <li>{place.city}</li>
                    </div>
                )
        });
        return(
            <div className = "container">
                <div className="content text-align-center">
                    <div className="row text-xs-center">
                        <div className="middle-text"  style={margin}>
                            <h1 className="welcome"><span>Welcome </span></h1>
                            <button ref="test" className="btn how-it-works" onClick={this.handleClick}>Search Space</button>
                        </div>
                    </div>
                </div>
                <div id="mySearch" className="overlay"  onKeyDown={this.handleKeyDown}>
                  <button className="btn closebtn" onClick={this.handleClick}>x</button>
                  <div className="overlay-content">
                        <SearchInput ref="searchInput" className="search-input" onChange={this.searchUpdated} />
                        <ul>{location}</ul>
                  </div>
            </div>
            </div>
            );
    }
}

1 个答案:

答案 0 :(得分:2)

我认为你要找的是encodeURIComponent

search( query='kathmandu' ){

let url = 'http://localhost:8000/api/v1/rental/?place__startswith=' + encodeURIComponent(query);

注意,由于您的查询字符串实际上只包含字母,因此该示例不需要encodeURIComponent,但在其他情况下可能需要它。