JSON 不是由独立的块组成的。所以这永远不会:
foreach($this->settings_model->get_state_list() as $state)
{
echo json_encode(array($state->CODSTA, $state->STANAM));
}
输出将被视为text,迭代器将循环对象的元素......这是单个字符。
您需要声明一个列表或字典。我已经包含了一些示例,具体取决于您在 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 回调中,您可以使用 charset 指定数据类型和内容类型(这将在您遇到像奥兰群岛这样的状态时派上用场,其中服务器以 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");
}