dqwh0109 2014-02-05 16:06
浏览 46

使用PHP + MySQL构建的使用Array对象的JQuery自动完成

I have a MySQL table like:

name   | id
John   | 1
Mike   | 2
Kelly  | 3

In Jquery, I'm able to use autocomplete showing "name" in the pop-up list while inserting the "id" in the input:

var names=[
    {label:"John", value:1},
    {label:"Mike", value:2},
    {label:"Kelly", value:3}
];
$('#myDiv').autocomplete({
    source: names
})

This is working fine, but now I need to reproduce the array of objects "names" using PHP. I'm trying the following in PHP:

$sql ="SELECT id, nome FROM table";
    $result = $pdo->query($sql);
    $rows = $result->fetchAll(PDO::FETCH_ASSOC);

    $output=array();;

    foreach($rows as $key){
        array_push($output, array($key{"nome"}=>intval($key{"id"})));
    };

    echo json_encode($output);

This is returning:

[{"John":1},{"Mike":2},{"Kelly":3}]

In Jquery, I'm now using Ajax to call myscript.php:

var names= [];
    $.ajax({
        url: "../myscript.php",
        success: function (response) {
            names = response.split(",");
        }
    });

But this is just displaying the same result in the cell:

[{"John":1},{"Mike":2},{"Kelly":3}]

So, I guess the soulution is to add label and value to each of the objects in PHP, or what can solve the problem?

Thanks in advance for any help!

  • 写回答

1条回答 默认 最新

  • douxian7534 2014-02-05 16:15
    关注

    You need to use the PHP header() method to do:

    header('CONTENT-TYPE: application/json');
    echo json_encode($output);
    

    might want to reference documentation in case I have a typo there :)

    But in any case, once the return type of the JSON is the right content-type, JQuery will automatically convert that response into an array of objects.

    [edit] Addendum...to the second part of your question:

    For auto-complete to work it depends on your IDE...and your IDE depends on an object definition within the same language that you are using. I use phpStorm. So, if I wanted to make auto-complete work in phpStorm for the JavaScript AJAX return, I would have to create a dummy JavaScript object (this can be anywhere in your code, even an un-used JS file that is there solely to define dummy objects...just has to have a unique name parseable by your IDE):

    //dummy object used for auto-completion to work
    function NameObject(param, param2) {
        this.label = param;
        this.value = param2;
    }
    

    Then, on my AJAX return, I would have to put:

    success: function(response) {
        /** @var NameObject[] response */
    }
    

    I dont' know of any other way to do this, and how well that would work depends on the IDE. I've never done this for JavaScript as it seems to be more work than it's worth.

    [edit2] Addendum on formatting PHP to output objects with named keys Okay, maybe I misunderstood...didn't notice at first that your labels weren't in the JSON you were outputting....so in your PHP, if you want the .label and .value to work, your PHP needs to generate it like so:

    $results = array();
    foreach($rows as $key){
        $obj        = new stdClass();
        $obj->label = $key['nome'];
        $obj->value = intval($key['id']);
        $results[]  = $obj;
    };
    echo( json_encode($results) );
    

    OR

    $results = array();
    foreach($rows as $key){
        $arr          = array();
        $arr['label'] = $key['nome'];
        $arr['value'] = intval($key['id']);
        $results[]    = $arr;
    };
    echo( json_encode($results) );
    
    评论

报告相同问题?

悬赏问题

  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?