状态200正常,相同的域,有效的JSON数据和无响应(Ajax)

这是我的ajax电话:

$.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 = ""; $.each(json, function(key, value) { options += '' + value + ''; }); $(".cidades").html(options); if (!filterThroughCEP) { $(".cidades").trigger("chosen:updated"); } }, error: function(e) { console.log(e.responseText); } }); 

这是php动作:

 if ($acao == 'filtrarCidades') { $estado_id = $_POST['estado_id']; $cidade->where = "estado_id = '".$_POST['estado_id']."'"; $cidade->LoadFromDB(); for ($c=0; $citens); $c++) { $cidades[$cidade->itens[$c]->id] = $cidade->itens[$c]->nome; } echo json_encode($cidades); die(); } 

json_encode($cidades)是有效的json数据(UTF8),这是使用debug的一个例子:

 {"1778":"Bras\u00edlia"} 

这个{"1778":"Bras\u00edlia"}作为e.responseText(错误),即使状态为OK,并且URL在同一个域上(不需要JSONP)。 我不知道为什么我无法取得success

编辑:我已设置contentType:

 contentType: "application/json", 

呼叫仍然无法“达到”成功。 这是第三个错误参数:

 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. (http://localhost/sisconbr-sistema-novo/site/visual/js/jquery.js:7835:9) 

它确实与来自数据库的字符串中的unicode字符有关。

编辑2 :我再次写了整篇文章,现在更清楚了:

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

PHP:

 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"}] 

错误:

 Uncaught SyntaxError: Unexpected token 

我认为问题是对象属性{“1778”:“Bras \ u00edlia”}表示具有无效属性名称的对象,因此json解码失败; 要certificate这是正确的尝试

  1. 使用纯文本作为dataType并记录它,它应该工作[但当然你将无法将其转换为json]
  2. changeLoadFromDB方法,以便属性名称有效[以letter,_或$开头],您将获得有效的JSON响应,但您需要更改使用它的方式

它1778是一个ID,一个合适的结构应该是{id:“1778”,属性:“Bras \ u00edlia”}并且工作完美无瑕试试让我们知道

编辑:正如jcaron亲切地建议的那样,我必须修复,这个答案:“1778”确实是一个有效的属性名称,但如果使用了点符号,则无效的标识符。 由于我不知道jQuery如何管理这个,我建议如上所述进行测试,看看其中一个测试是否给出了结果。