2012-10-17 22 views
0

我需要能够在选择框中选择一个国家,然后获取该国家的所有国家。使用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)); 
} 

和我的javascript:

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

的console.log表明我是这样的:

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

所以,我需要的是在新的选择框中追加所有状态。

但我试图读取该数组中的成功回调做这个:

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

在结果中,每一行是一个词,就像这样:

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

为什么说发生,我错过了什么?

+2

这是因为你在一个时间呼应每个编码阵列的..你需要将它们都添加到一个数组..然后编码和回声 –

回答

5

JSON不是由独立块。因此,这绝不会做的事:

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

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

您需要声明一个列表或字典。我已经包含了一些示例,具体取决于您在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)); 

在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"); 
      } 
+0

是的,现在一切都更加清晰的php,将继续与jquery加载结果。 –

0

您应该使用GET不是POST,因为您实际上并没有创建任何新的服务器端。 阅读关于REST的一些信息,以及为什么使用GET在这里是专有名词。

我已经添加了一个JSFiddle示例,可以直接运行。 http://jsfiddle.net/KJMae/26/

如果是这样的JSON的PHP服务回报:

{ 
    "success":true, 
    "states":[ 
     { 
      "id":71, 
      "name":"California" 
     }, 
     { 
      "id":72, 
      "name":"Oregon" 
     } 
    ] 
} 

这是我们的HTML代码:

<select id="country"> 
    <option value="">No country selected</option> 
    <option value="1">USA</option> 
</select> 

<select id="states"> 
</select>​ 

这是什么代码,这增加了选择可能看起来像:

// Bind change function to the select 
jQuery(document).ready(function() { 
    jQuery("#country").change(onCountryChange); 
}); 

function onCountryChange() 
{ 
    var countryId = jQuery(this).val();  

    $.ajax({ 
     url: '/echo/json/', 
     type: 'get', 
     data: { 
      countryId: countryId 
     }, 
     success: onStatesRecieveSuccess, 
     error: onStatesRecieveError 
    }); 
} 

function onStatesRecieveSuccess(data) 
{ 
    // Target select that we add the states to 
    var jSelect = jQuery("#states"); 

    // Clear old states 
    jSelect.children().remove(); 

    // Add new states 
    jQuery(data.states).each(function(){   
     jSelect.append('<option value="'+this.id+'">'+this.name+'</option>'); 
    }); 
} 

function onStatesRecieveError(data) 
{ 
    alert("Could not get states. Select the country again."); 
}​ 

至于PHP,下面是一个简单的例子,应该给出与上例中使用的JSON相同的结果。 (没有测试过,从我的头,在这里没有PHP的顶部)。

$result = new stdClass; 
$result->states = array(); 

foreach($this->settings_model->get_state_list() as $state) 
{ 
    $stateDto = new stdClass(); 
    $stateDto->id = $state->CODSTA; 
    $stateDto->name = $state->STANAM; 

    $result->states[] = $stateDto; 
} 

$result->success = true; 

die(json_encode($result)); 
相关问题