[英]Passing variable value from one function to another in autocomplete with AJAX call
I have a problem in using autocomplete jQuery with AJAX call. 我在通过AJAX调用使用自动完成jQuery时遇到问题。 When user types something in input field, I post that value with AJAX to controller where I get the values from database and then all these values to the JavaScript in success message.
当用户在输入字段中键入内容时,我将使用AJAX将该值发布到控制器,从数据库中获取值,然后将所有这些值发送到成功消息中的JavaScript。 But after that, I'm having problem to use these JSON values for autocomplete.
但是在那之后,我在使用这些JSON值进行自动完成时遇到了问题。 How to fix that?
如何解决?
The view file 查看文件
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.0/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.0/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<script>
$(function() {
$("#tags").autocomplete({
source: function( request, response ) {
$.ajax({
type: "POST",
url: "<?php echo base_url().'index.php/search_con/user' ;?>",
data: {'userA': request.term},
success: function(msgs)
{
var a = ["Central Palms Hotel","Hotel Monalisha","asghgjfddas","My hotel added","asdfsdf","asdsadsa"];
response(a);
// alert(msgs);
}
});
}
});
});
</script>
<div class="ui-widget">
<label for="tags">Tags:</label>
<input id="tags">
</div>
and the controller 和控制器
public function user(){
$userPart = $_POST['userA'];
$result = $this->searchdb->search($userPart) ;
$list = array();
foreach ($result as $finaldata) {
$data= $finaldata->name;
array_push($list, $data);
}
echo json_encode($list);
}
Now my problem is that when i remove static variable a and use msgs for response nothing is shown in autocomplete data and when alert msgs i get the same data as in variable a. 现在我的问题是,当我删除静态变量a并使用msgs进行响应时,自动完成数据中未显示任何内容,而警报msgs则获得与变量a中相同的数据。 is there any mistake in my json?
我的json有任何错误吗?
You don't need to have separate function to fetch the data for autocomplete, can be done like this 您不需要单独的功能来获取数据以完成自动填充,可以这样完成
$(function () {
$("#tags").autocomplete({
source: function (request, response) {
$.post("<?php echo base_url().'index.php/search_con/user' ;?>", {
userA: request.term
}, response);
}
});
});
And because of the async nature of ajax you cant do this 而且由于ajax的异步特性,您不能这样做
$.ajax({
type: "POST",
url: "<?php echo base_url().'index.php/search_con/user' ;?>",
data: dataString,
success: function (msgs) {
data = msgs;
}
});
alert(data); // undefined
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.