jQuery的自动完成Ajax响应分离 [英] jquery autocomplete ajax response separation

查看:102
本文介绍了jQuery的自动完成Ajax响应分离的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

HTML部分:

  <form method="post" id="src-form" name="src-form" action="<?php echo $SCRIPT_NAME; ?>">

          <input id="src-location" name="src-location" autocomplete="off" />

          <input type="submit" name="src_submit" id="src_submit" value="Search" />

        </form>

    <script>

      $(document).ready(function() {

        $("input#src-location").autocomplete({

     source: "autosuggest-server.php"
        });

       $('input#src-location').focus(function()

        {       

                $(this).val('');


        });  

    });  

    </script>

PHP的一部分:

<?php

include("db.php");

$return_arr = array();


$fetch = mysql_query("SELECT * FROM city INNER JOIN country ON country.countryid = city.countryid where cityname like '%" . mysql_real_escape_string($_GET['term']) . "%' ORDER BY cityname ASC limit 0,20"); 

    while ($row = mysql_fetch_array($fetch, MYSQL_ASSOC)) {

        $row_array['id'] = $row['id'];

        $row_array['value'] = $row['cityname'].", ".$row['countryname'];

        array_push($return_arr,$row_array);
    }

echo json_encode($return_arr);
?>

记者: 正常的jQuery自动提示脚本

JS: Normal jquery autosuggest script

在PHP文件,我已经添加了:

$row_array['value'] = $row['cityname'].", ".$row['countryname_'.$lang].",".$row['cityid'];

当我输入的东西它回声获得预期的cityid。有没有什么办法了cityid从实际的显示值分开,并给它一个隐藏输入文本字段?

When I type in something it echos out the cityid as expected. Is there any way to separate the cityid from the actual displayed value and feed it into a hidden input text field?

我想要做的就是通过cityid进行搜索,但我不希望它在搜索字段中显示。

What I want to do is to search by the cityid but I don't want it to show in the search field.

任何其他的解决办法?

Any other solutions?

非常感谢。

推荐答案

我建议你返回响应作为JSON对象,所以在PHP你做的:

I suggest you return the response as a JSON object, so in php you do:

$dataArray = ... //get city data where key=cityId, value=1, key=cityName, value=London etc.
echo json_encode($dataArray);

这将返回类似:

{'cityId':'1','cityName':'London'}

现在在JavaScript中,定义你的Ajax请求,接受JSON加入:

Now in the javascript, define your ajax request to accept json by adding:

dataType: 'json'

,一旦你得到响应消息,你可以这样做:

and once you get the response message you can do:

$('#myHiddenField').val(msg.cityId);
var cityName = msg.cityName;
//do whatever you like with cityName

这篇关于jQuery的自动完成Ajax响应分离的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆