JQuery Autocomplete, populate with data from pHp json

前端 未结 4 621
鱼传尺愫
鱼传尺愫 2021-01-07 09:39

I am returning a JSON encoded array: echo(json_encode($data)); from php and I would like it to populate the suggest box from JQuery autocomplete. I\'m using thi

相关标签:
4条回答
  • 2021-01-07 10:23

    Somthing like this is the best way. json_encode do all work for you.

        $result = $_mysqli->query(...);
        $rs = array();
        $pos = 0;
        while($row = $result->fetch_assoc()){
            $rs[$pos]["n1"] = $row["n1"];
            $rs[$pos]["n2"] = $row["n2"];
            ...
            $rs[$pos++]["nn"] = $row["nn"];
    
        }
        header('Content-type: application/json');
        echo json_encode($rs);
    
    0 讨论(0)
  • 2021-01-07 10:38

    Maybe something wrong with the source parameter. Should it be '/Searchtest.php'?

    http://api.jqueryui.com/autocomplete/#option-source

    0 讨论(0)
  • 2021-01-07 10:42

    Try using ajax

    var searchRequest = null;
    $("#field").autocomplete({
        maxLength: 5,
        source: function(request, response) {
            if (searchRequest !== null) {
                searchRequest.abort();
            }
            searchRequest = $.ajax({
                url: 'SearchTest.php',
                method: 'post',
                dataType: "json",
                data: {term: request.term},
                success: function(data) {
                    searchRequest = null;
                    response($.map(data.items, function(item) {
                        return {
                            value: item.name,
                            label: item.name
                        };
                    }));
                }
            }).fail(function() {
                searchRequest = null;
            });
        }
    });
    

    JSON Response Example in SearchTest.php

    <?php
    header('Content-type: application/json');
    echo '{"items":[{"name":"Ashok"},{"name":"Rai"},{"name":"Vinod"}]}';
    ?>
    

    Demo Fiddle

    Remote JSONP Demo

    0 讨论(0)
  • 2021-01-07 10:43

    the proper json format for this from php:

    <?php
       echo '[ {"name1":"val1"},{"name2":"val2"} ]'; 
    ?>
    

    From js wich means []-array of {} objects.

    In my case for autocomlete widjet this works fine:

        $response="[";
        while($row = $res->fetch_assoc()){
            if($response !="[")$response.=",";
            $response.='{"label":"'.$row["fio"].'","value":"'.$row["id"].'"}';
        }
        $response.="]";
    
        echo $response;
    
    0 讨论(0)
提交回复
热议问题