douzhuo1853 2012-10-17 20:48
浏览 41
已采纳

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

I need to be able to select a country in a selectbox, and then get all the states from that country.

I'm trying to do something like this: how-to-display-json-data-in-a-select-box-using-jquery

This is my controller:

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

and my javascript:

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

console.log shows me something like this:

["71","SomeState0"]["72","SomeState"]["73","SomeState2"]["74","SomeState3"]

So, what i need is to append all states in a new selectbox.

But I'm trying to read this array doing this in the success callback:

$.each(data, function(key,val){
   console.log(val);
});

In the result, each line is a word, like this:

[
 "
 7
 1
 "
 ,
 "
 s
 ....
 ]

Why does that happen, and what am I missing?

  • 写回答

3条回答 默认 最新

  • douzhuang6321 2012-10-17 20:54
    关注

    JSON is not made of independent blocks. So this will never do:

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

    The output will be treated as text, and the iterator will loop the object's elements... which are the single characters.

    You need to declare a list, or a dictionary. I have included some examples, depending on how you use the data in the jQuery callback. Note: PHP-side, you may also need to output the proper MIME type for JSON:

    $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));
    

    In the jQuery callback, you specify the datatype and content type with charset (this will come in handy as soon as you encounter a state such as the Åland Islands, where a server sending data in ISO-8859-15 and a browser running a page in UTF8 can lead to a painful WTF moment):

            $.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");
               }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效