我可以通过JavaScript调用函数吗?

时间:2015-03-24 07:57:44

标签: javascript html

您好我想在数据库中运行搜索单词的功能。该功能位于此位置:媒体/搜索,到目前为止,可以通过“search_query”使用此JS运行此功能:

final_transcript = capitalize(final_transcript);   
    var queryTextField = document.getElementById("search_query");  
    queryTextField.value = final_transcript;       
   ....

“search_query”在此输入中为id:

<form class="input-group navbar-form" action="<?php echo base_url();?>media/search" method="post"></li>
                <li style="margin-top:8px;"><input type="text" class="form-control" placeholder="Search subtitles..." id="search_query" name="string" /></li>   
                <li style="margin:8px><button type="submit" class="btn btn-info" name="btn_search"><i class="search "></i></button>

我想更改它,所以我不想使用此HTML代码。我想在JS中实现“调用”功能媒体/搜索,而不是:

 var queryTextField = document.getElementById("search_query");  

1 个答案:

答案 0 :(得分:0)

如果我误解了你,请告诉我,但如果我理解正确,你想用javascript触发搜索吗?

看起来你想在没有jQuery的情况下这样做吗?

//get search string inputted by user
var queryTextField = document.getElementById("search_query");
var query = queryTextField.value

//pass base url to javascript
var base_url = '<?php echo base_url();?>'

//create new request
var request = new XMLHttpRequest();

//set up what you want to do with returned data
request.onreadystatechange=function()
{
  //if call was successful
  if (request.readyState==4 && request.status==200)
  {  
     //response will be in here  
     //request.responseText;
  }
}

//set as post, the url, send asynchronously
request.open('POST', base_url+'media/search', true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
request.send(query);

使用jQuery:

$.ajax({
  type: 'POST',
  url: base_url+'media/search',
  data: query,
  success: function(data_return) {
    //do something with returned data
  }
});

见:

https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest

http://api.jquery.com/jquery.ajax/

我没有测试过上面的代码,但它应该让你走上正确的道路。