json_encode将空数组放在json的末尾

I'm writing an ajax application and have a function in a php script:

public function expire_user() {
    $r=array("return"=>'OK');
    echo json_encode($r); 
}

that gets called with this javascript:

$.getJSON("/users/expire_user",function(data){
        alert('success');
});

The problem is that the alert never displays. I think this is due to json_encode returning invalid json, because when I go to the url directly, it displays

{"return":"OK"}[]

which is not valid json due to the extra '[]' on the end. Why is json_encode putting the empty array on the end and how do I get rid of it so that I can receive valid json?

Wild guess, but maybe you should set correct headers for the JSON in your PHP function like this:

public function expire_user() {
    $r=array("return"=>'OK');
    header("Content-type: application/json");
    echo json_encode($r); 
}

Or actually send the content as X-JSON headers like this:

public function expire_user() {
    $r=array("return"=>'OK');
    $json_data = json_encode($r);
    header('X-JSON: (' . $json_data . ')');
    header('Content-type: application/x-json');
    echo $json_data;
}

A bit rusty on whether when using X-JSON the accompanying header should be application/x-json or just the normal application/json, but adding this caveat to help you debug.

This isn't quite an "answer", but I'm assuming your script is running some other code (maybe echo json_encode(array());) some time after expire_user() is called. To ensure that this is the last thing called you can use die() or exit():

public function expire_user() {
    $r = array("return"=>'OK');
    die(json_encode($r));
}

However, I suggest you try to debug the real problem. For instance, if you have a URL router than is handling requests and calling methods..it could be errantly echoing extra characters (that may cause more problems down the line). If you post your code that calls expire_user(), I can help debug further.


Disclaimer: I do not consider this a production-worthy solution. It needs more debugging, though.