如何将id变量转换为ajax

时间:2017-06-29 15:05:35

标签: javascript html ajax

JS

function SearchInList(_id,_url,_place){
    this.id = _id;
    this.url = _url;
    this.place = _place; /*How to get this value */
};
SearchInList.prototype.FindMe = function (_str){
this.str = _str;
   if (this.str == "") {
         if (window.XMLHttpRequest) {
            // code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp = new XMLHttpRequest();
        } else {
            // code for IE6, IE5
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        var place = this.place;
        xmlhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                document.getElementById("lista-ind").innerHTML = this.responseText;   /*in this place */
            }
        };
        xmlhttp.open("GET",this.url+"?id="+this.id,true);
        xmlhttp.send();
   } else { 
        if (window.XMLHttpRequest) {
            // code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp = new XMLHttpRequest();
        } else {
            // code for IE6, IE5
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                document.getElementById("lista-ind").innerHTML = this.responseText;
            }
        };
        xmlhttp.open("GET",this.url+"?id="+this.id+"&hint="+this.str,true);
        xmlhttp.send();
    }
};
HTML中的

我有

<input type="text" placeholder="Search" id="search-ind" ></div>
    <div id="lista-ind" class="lista"></div>
<script>
    var id = <?php echo $_GET['id']; ?>;
    var url = "showresults.php";
    var place = "lista-ind";

    var searchInd = new SearchInList(id, url);
    var searchboxInd = document.getElementById("search-ind");

    window.onload = searchboxInd.addEventListener("keyup", function(){
        searchInd.FindMe(searchboxInd.value,place);
        console.log(searchboxInd.value);
    }, false);  

    window.onload = searchInd.FindMe("",place);

</script>

当我在onreadystatechange中运行时“document.getElementById(”lista-ind“)”它正在工作,但当我改为  document.getElementById(this.place)它不是。

如何将此变量传递给该函数?

这就是我在列表中搜索的方式。 谢谢。 微米。

2 个答案:

答案 0 :(得分:0)

如果place是全局变量,在函数外部,则不需要this;只是变量名。

document.getElementById(place)

答案 1 :(得分:0)

您在没有地点的情况下实例化SearchInList并且FindMe不会作为参数进行实例化,因此无法在对象中使用该地点。
最简单的解决方案是将地点作为参数添加到FindMe

SearchInList.prototype.FindMe = function (_str, _place){
  this.str = _str;
  this.place = _place;
  ...