简体   繁体   中英

Status 200 OK, same domain, valid JSON data and no response (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);
        }
    });

Here's the php action:

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) is valid json data (UTF8), here's one example using debug:

{"1778":"Bras\u00edlia"}

This {"1778":"Bras\ília"} 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 .

EDIT: 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)

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

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

Output:

[{"id":"1778","estado_id":"7","nome":"Brasília","cep":"","loc_no_abrev":"Brasília"}]

Error:

Uncaught SyntaxError: Unexpected token 

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

  1. use plain text as dataType and log it, it should work [but of course you will not be able to convert it to json]
  2. changeLoadFromDB method so that property name is valid [starts with letter, _ or $], you will have a valid JSON response, but you will need to change the way you use it

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

EDIT: 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM