本文介绍了状态200正常,相同的域,有效的JSON数据且无响应(Ajax)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的ajax电话:

Here's my ajax call:

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

这是php动作:

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_encode($cidades)是有效的json数据(UTF8),这是一个使用debug的示例:

json_encode($cidades) is valid json data (UTF8), here's one example using debug:

{"1778":"Bras\u00edlia"}

即使状态为OK,此{"1778":"Bras\u00edlia"}也将作为e.responseText(错误)出现,并且URL在同一域中(不需要JSONP).我不知道为什么我无法达到success.

This {"1778":"Bras\u00edlia"} goes as e.responseText (Error), even with Status OK, and the URL is on the same domain (No need for JSONP). I have no idea why I can't reach success.

我已经设置了contentType:

I've set the contentType:

contentType: "application/json",

并且呼叫仍然无法达到"成功.这是第三个错误参数:

And the call still can't "reach" success. Here's the third error argument:

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)

它确实与数据库字符串内部的unicode字符有关.

It is indeed related to unicode characters inside the strings that come from the database.

EDIT2 :我再次写了整个内容,现在更清楚了:

EDIT2: I wrote the whole thing again, and now it's clearer:

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解码失败;要证明这是否正确,请尝试

I think that the problem is the object property{"1778":"Bras\u00edlia"}means an object with an invalid property name, thus json decoding fails;to prove if this is right try either

  1. 使用纯文本作为dataType并将其记录下来,它应该可以工作[但是,您当然不能将其转换为json]
  2. changeLoadFromDB方法,以便属性名称有效(以字母,_或$开头),您将具有有效的JSON响应,但您需要更改其使用方式

1778是一个ID,应使用正确的结构{id:"1778",property:"Bras \ u00edlia"},并且可以正常工作试试看,让我们知道

it 1778 is an ID, a proper structure should be{id:"1778",property:"Bras\u00edlia"} and work flawlessgive it a try and let us know

根据 jcaron 的建议,我必须解决此问题:"1778"确实是有效的属性名称,但无效标识符(如果使用点表示法).由于我不知道jQuery如何处理此问题,因此我建议按上述方法进行测试,并查看其中一项测试是否能够得出结果.

as jcaron kindly suggested, i have to fix, this answer: the "1778" is indeed a valid property name, but invalid identifier if dot notation is used.Since I don't know how jQuery manage this i would suggest to test as above, and see if one of the tests gives results.

这篇关于状态200正常,相同的域,有效的JSON数据且无响应(Ajax)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 21:38