简体   繁体   English

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

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

I want to pass an array of data from php to typeahead, but its not working, I dont know what I am doing wrong.我想将一组数据从 php 传递到 typeahead,但它不起作用,我不知道我做错了什么。 I have checked other questions but unable to get solution.我已经检查了其他问题,但无法获得解决方案。 I tried displaying the response on console and it displays the array of strings but nothing in typeahead field我尝试在控制台上显示响应,它显示字符串数组,但在 typeahead 字段中没有任何内容

PHP PHP

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

JS 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 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)
        });

The problem is you are trying to return something on ajax success function.问题是你试图在 ajax 成功函数上返回一些东西。 In that case it is impossible because ajax doing async request.在这种情况下,这是不可能的,因为 ajax 正在执行异步请求。 Write your code like this.像这样写你的代码。

$.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