PHP JSON不起作用,有人能告诉我为什么吗


PHP JSON does not work, can anyone tell me why?

myfile.php

header('Content-type: application/json');
echo json_encode( array( 'error' => 'jkfshdkfj hskjdfh skld hf.' ) );

上面的代码是有效的。

但当我更改它时,它停止工作:

if( isset( $_GET['customerID'] ) ){
       // do something else error
} else {
   header('Content-type: application/json');
   echo json_encode( array( 'error' => 'jkfshdkfj hskjdfh skld hf.' ) );
}

两个输出都是正确的:

{"error":"jkfshdkfj hskjdfh skld hf."}

但是我得到一个ajax错误:

myfile.phtml

        <?php 
            if( isset( $_GET['custID'] ) )
               echo "var custID = " . htmlentities( $_GET['custID'] ) . ";";                             
            else
               echo "var custID = null;";                             
        ?>
        $.ajax({
            url: 'php/viewCustomer.php',
            type: 'GET',
            data: {customerID: custID},
            dataType: 'json',
            cache: false,
            beforeSend: function(){
                $('#display').append('<div id="loader"> Lodaing ... </div>');
            },
            complete: function(){
                $('#loader').remove();
            },
            success: function( data ){
                if( data.error ) {
                    var errorMessage = "";
                    $.each( data, function( errorIndex, errorValue ){ 
                        errorMessage += errorValue + "'n";
                    });
                    alert( errorMessage );
                } else {
                    //$('div#customer-content table tr td').eq(0).text( '1234' );
                    //$('div#customer-content table tr td').eq(1).text( '1234' );
                    //$('div#customer-content table tr td').eq(2).text( '1234' );
                    //$('div#customer-content table tr td').eq(3).text( '1234' );
                    //$('div#customer-content table tr td').eq(4).text( '1234' );
                    alert( data );
                }                       
            },
            error: function( jqXHR ){
                alert( 'AJAX ERROR' );
            }
        });
    });

从注释中可以看出,您正在传递一个空的customerID,而不希望它进入if条件。但是,即使该值为空,$_GET['customerID']仍然被设置。将检查改为empty(),它将如您所期望的那样工作:

if( !empty( $_GET['customerID'] ) ){
    ....