使用jQuery .each()从数据库中读取JSON到组合框中

Ric*_*nns 0 php jquery json

我需要能够在选择框中选择一个国家/地区,然后获取该国家/地区的所有州.

我正在尝试做类似这样的事情:how-to-display-json-data-in-a-select-box-using-jquery

这是我的控制器:

foreach($this->settings_model->get_state_list() as $state)
{
   echo json_encode(array($state->CODSTA, $state->STANAM));
}
Run Code Online (Sandbox Code Playgroud)

和我的javascript:

 $.ajax({
    url: 'settings/express_locale',
    type: 'POST',
    data: { code: location, type: typeLoc },
    success: function (data) {
        console.log(data);
    }
});
Run Code Online (Sandbox Code Playgroud)

console.log向我展示了这样的事情:

["71","SomeState0"]["72","SomeState"]["73","SomeState2"]["74","SomeState3"]
Run Code Online (Sandbox Code Playgroud)

所以,我需要的是将所有状态附加到新的选择框中.

但我试图在成功回调中读取此数组:

$.each(data, function(key,val){
   console.log(val);
});
Run Code Online (Sandbox Code Playgroud)

在结果中,每一行都是一个单词,如下所示:

[
 "
 7
 1
 "
 ,
 "
 s
 ....
 ]
Run Code Online (Sandbox Code Playgroud)

为什么会这样,我错过了什么?

LSe*_*rni 5

JSON不是由独立块组成的.所以这永远不会做:

foreach($this->settings_model->get_state_list() as $state)
{
    echo json_encode(array($state->CODSTA, $state->STANAM));
}
Run Code Online (Sandbox Code Playgroud)

输出将被视为文本,迭代器将循环对象的元素...这是单个字符.

您需要声明列表或字典.我已经包含了一些示例,具体取决于您如何在jQuery回调中使用数据.注意:在PHP端,您可能还需要为JSON输出正确的MIME类型:

$states = array();
foreach($this->settings_model->get_state_list() as $state)
{
    // Option 1: { "71": "SomeState0", "72": "Somestate2", ... }
    // Simple dictionary, and the easiest way IMHO
    $states[$state->CODSTA] = $state->STANAM;

    // Option 2: [ [ "71", "SomeState0" ], [ "72", "SomeState2" ], ... ]
    // List of tuples (well, actually 2-lists)
    // $states[] = array($state->CODSTA, $state->STANAM);

    // Option 3: [ { "71": "SomeState0" }, { "72": "SomeState2" }, ... ]
    // List of dictionaries
    // $states[] = array($state->CODSTA => $state->STANAM);
}

Header('Content-Type: application/json');
// "die" to be sure we're not outputting anything afterwards
die(json_encode($states));
Run Code Online (Sandbox Code Playgroud)

在jQuery的回调,可以指定数据类型和内容类型与字符集(这将只要你碰到的状态,如奥兰群岛,其中一个服务器在ISO-8859-15发送数据和浏览器中运行的页面派上用场在UTF8中会导致一个痛苦的WTF时刻):

        $.ajax({
            url: 'settings/express_locale',
            type: 'POST',
            data: { code: location, type: typeLoc },
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {
                $("#comboId").get(0).options.length = 0;
                $("#comboId").get(0).options[0] = new Option("-- State --", "");
                // This expects data in "option 1" format, a dictionary.
                $.each(data, function (codsta, stanam){
                   n = $("#comboId").get(0).options.length;
                   $("#comboId").get(0).options[n] = new Option(codsta, stanam);
             });
           },
           error: function () {
                alert("Something went wrong");
           }
Run Code Online (Sandbox Code Playgroud)