繁体   English   中英

无法使用 php 将 json 数据传递给预先输入

[英]Unable to pass json data to typeahead with php

我想将一组数据从 php 传递到 typeahead,但它不起作用,我不知道我做错了什么。 我已经检查了其他问题,但无法获得解决方案。 我尝试在控制台上显示响应,它显示字符串数组,但在 typeahead 字段中没有任何内容

PHP

$resp = array();
        $states = $this->cj_model->list_all_states();
        foreach($states as $row){
            $resp[] = $row['name'];
        }
        echo json_encode($resp);

JS

var substringMatcher = function(strs) {
    return function findMatches(q, cb) {
        var matches, substringRegex;

        // an array that will be populated with substring matches
        matches = [];

        // regex used to determine if a string contains the substring `q`
        substrRegex = new RegExp(q, 'i');

        // iterate through the pool of strings and for any string that
        // contains the substring `q`, add it to the `matches` array
        $.each(strs, function(i, str) {
            if (substrRegex.test(str)) {
                matches.push(str);
            }
        });

        cb(matches);
    };
};

AJAX

 function get_states()
    {
        $.ajax({
            url:  'country/get_states/',
            dataType: 'json',
            type: 'get',
            async: true,
            success: function(response){
               return (response);
            },
            error: function(jqxhr, textStatus, error){
                console.log(error);
            }
        });
    }

   var states = get_states();

   $('.typeahead').typeahead({
            hint: true,
            highlight: true,
            minLength: 1
        },
        {
            name: 'states',
            source: substringMatcher(states)
        });

问题是你试图在 ajax 成功函数上返回一些东西。 在这种情况下,这是不可能的,因为 ajax 正在执行异步请求。 像这样写你的代码。

$.ajax({
            url:  'country/get_states/',
            dataType: 'json',
            type: 'get',
            async: true,
            success: function(response){
               $('.typeahead').typeahead({
                    hint: true,
                    highlight: true,
                    minLength: 1
                  },
                  {
                   name: 'states',
                   source: substringMatcher(states)
              });
            },
            error: function(jqxhr, textStatus, error){
                console.log(error);
            }
        });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM