使用$ .post自动填充无法按预期工作

时间:2015-08-06 09:37:47

标签: javascript php autocomplete

使用this commadelimited autocomplete我创建了一个 php 文件,从我的MySQL数据库中获取一些已创建的 php 脚本的值

<?php
$connection = mysql_connect("my_host", "usr", "pwd"); // Establishing connection with server..
$db = mysql_select_db("appdb", $connection); 
$wid =$_POST['wid1'];
$result = mysql_query("select * from shop where wid=$wid");
$to_encode = array();
$data = mysql_num_rows($result);
if ($data > 0){
    while($row = mysql_fetch_assoc($result)) {
  $to_encode[] = $row;
}
echo json_encode($to_encode);
}
else{
    echo "No Shops Available, Contact Your Wholesaler !!";
}
mysql_close ($connection); // Connection Closed.
?>

我在JavaScript中创建了一个函数来将值提取到变量

$.post("http://theurl.com/app/get_shopname.php",{ wid1:10},
function(shopnames){
if(shopnames=='No Shops Available, Contact Your Wholesaler !!'){
$('input[type="text"],input[type="searchField"]').css({"border":"2px solid red","box-shadow":"0 0 3px red"});
alert(shopnames);
}else{

var availableTags = shopnames;
}
    }


    );

$("#searchField").autocomplete({
    target: $('#suggestions'),
    source: availableTags,
    link: 'target.html?term=',
    minLength: 1
});

问题是,当点击function(shopnames)它只是传递给下一个函数时,它不会进入$.post("http://theurl.com/app/get_shopname.php" ..函数内部

2 个答案:

答案 0 :(得分:1)

  1. 将$ _POST更改为$ _GET进行测试
  2. 在浏览器中加载网址http://theurl.com/app/get_shopname.php?wid1=10并看到它返回正确的JSON
  3. 更改回$ _POST并在echo
  4. 之前的某处添加header("Content-type: application/json");
  5. 确保在拥有数据之前不要调用自动填充事件处理程序
  6. 这样的事情:

    $(function) { // when page loads 
      var wid = "<?PHP echo $wid; ?>"; // for example
      $.post("http://theurl.com/app/get_shopname.php", { wid1: wid },
        function(shopnames) {
          if (shopnames == 'No Shops Available, Contact Your Wholesaler !!') {
            $('input[type="text"],input[type="searchField"]').css({
              "border": "2px solid red",
              "box-shadow": "0 0 3px red"
            });
          } else {
            var availableTags = [];
            $(shopnames).each(function(i,tag) {
              availableTags.push(tag.shopname);
            });
            $("#searchField").autocomplete({
              target: $('#suggestions'),
              source: availableTags,
              link: 'target.html?term=',
              minLength: 1
            });
        });
    });
    

答案 1 :(得分:0)

我打开浏览器开发工具中的“网络”标签,查看是否没有ajax请求结果的错误代码。这将使回调被跳过。只有在请求成功时才会被触发(代码200)。