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");
}
这是因为你在一个时间呼应每个编码阵列的..你需要将它们都添加到一个数组..然后编码和回声 –