这是我的ajax电话:
headers('Content-Type: application/json');
这是php动作:
$.ajax({
url : hostGlobal + "site/modulos/prefeitura/acoes-jquery.php",
type: "POST",
dataType : "JSON",
data: {
acao: "filtrarCidades",
estado_id: $(".estados:chosen").val()
},
success: function(json) {
console.log("worked");
$(".cidades").html('');
var options = "<option value=\"\"></option>";
$.each(json, function(key, value) {
options += '<option value="' + key + '">' + value + '</option>';
});
$(".cidades").html(options);
if (!filterThroughCEP) {
$(".cidades").trigger("chosen:updated");
}
},
error: function(e) {
console.log(e.responseText);
}
});
if ($acao == 'filtrarCidades') {
$estado_id = $_POST['estado_id'];
$cidade->where = "estado_id = '".$_POST['estado_id']."'";
$cidade->LoadFromDB();
for ($c=0; $c<count($cidade->itens); $c++) {
$cidades[$cidade->itens[$c]->id] = $cidade->itens[$c]->nome;
}
echo json_encode($cidades);
die();
}
是有效的json数据(UTF8),这是使用debug的一个例子:
json_encode($cidades)
此{"1778":"Bras\u00edlia"}
与e.responseText(错误)一样,即使状态为OK,并且URL位于同一域(不需要JSONP)。我不知道为什么我无法达到{"1778":"Bras\u00edlia"}
。
编辑:我已经设置了contentType:
success
呼叫仍然无法达到&#34;成功。这是第三个错误参数:
contentType: "application/json",
它确实与来自数据库的字符串中的unicode字符有关。
EDIT2 :我再次写了整篇文章,现在情况更清楚了:
SyntaxError: Unexpected token
at parse (native)
at ajaxConvert (http://localhost/sisconbr-sistema-novo/site/visual/js/jquery.js:7608:19)
at done (http://localhost/sisconbr-sistema-novo/site/visual/js/jquery.js:7363:15)
at XMLHttpRequest.<anonymous> (http://localhost/sisconbr-sistema-novo/site/visual/js/jquery.js:7835:9)
PHP:
function getCitiesByState() {
$.ajax({
url : hostGlobal + "site/estrutura/ajax.php",
type: "POST",
dataType : "text",
data: {
action: "getCitiesByState",
state_id: $(".estados option:selected").val()
},
success: function(json, textStatus, jqXHR) {
console.log($.parseJSON(json));
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
}
});
}
输出:
if ($_POST["action"] == "getCitiesByState") {
$cities = getResults("SELECT * FROM tbl_cidades WHERE estado_id = ".$_POST["state_id"]);
echo json_encode($cities, JSON_UNESCAPED_UNICODE);
die();
}
错误:
[{"id":"1778","estado_id":"7","nome":"Brasília","cep":"","loc_no_abrev":"Brasília"}]
答案 0 :(得分:-2)
我认为问题是对象属性 { “1778”: “胸罩\ u00edlia”} 表示具有无效属性名称的对象,因此json解码失败; 要证明这是正确的尝试
它1778是一个ID,应该是一个合适的结构 {id:“1778”,财产:“Bras \ u00edlia”}并且工作完美无缺 尝试一下,让我们知道
编辑: 如jcaron友好建议,我必须解决,这个答案:“1778”确实是一个有效的属性名称,但如果使用点表示法则无效的标识符。 由于我不知道jQuery如何管理这个我建议如上测试,看看其中一个测试是否给出结果。