简体   繁体   中英

ERROR Uncaught SyntaxError: Unexpected token <in JSON at position 0

I have the following JS script:

jQuery(document).ready(function($) {
    $("#idSelect").change(function(event) {
        var valor = $(this).val();
        //alert(valor);
        $.post( "ajaxSerie.php", { valorInput: valor }, function( data ) {
            var retorno = JSON.parse(data);
            console.log(retorno);
            $("#pertence").val(retorno['pertence'])// aqui estou atribuindo um input qualquer o valor retornado do php, o input tera o valor de sala206
            $.each(retorno, function() {
                $('<option>').val(retorno['pertence']).text(retorno['pertence']).appendTo('#teste');
            });
        });
    });

}

in AJAX looks like this:

$idValor = $_POST['valorInput']; 
 $result = [
"pertence" => $idValor
];
echo json_encode($result);

when I do local it works perfectly, now when I step to the site on the server the following error:

Uncaught SyntaxError: Unexpected token < in JSON at position 0

how to solve this?

Your Ajax call might be returning HTML, which begins with a '<', the beginning of the opening HTML tag.

In my experience, Ajax calls returning HTML is a sign that there has been an error in the back end. If you use your browser's developer tools, you'll be able to track your Ajax call and read its response.

Take the time to read that HTML, because most of the time, the error message in the tag leaves a breadcrumb to find the real problem.

1st: $.post(url , {} , callback function(){} , 'json'); you can add 'json' instead of using JSON.parse()

2nd: if your server is running a PHP version older than 5.4

$result = [
"pertence" => $idValor
];

should be

$result = array(
"pertence" => $idValor
);

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