AJAX将数据返回到jquery

I have an ajax call:

jQuery.ajax({
        type: "POST", // HTTP method POST or GET
        url: 'inc/functions.php?func=get_usr&id='+usr, //Where to make Ajax calls
        success:function(data){
            if (data.fname) {
             var fname = data.fname;
             //alert (fname);
            $('#rname').text(fname);
            }
         },
        error:function (xhr, ajaxOptions, thrownError){
           alert(thrownError);
        }
        });

data returns:

fname: "test_fname"
lname: "test_lname"
role: "1"

problem is I can get fname out of it, the alert shows undefined.
This doesnt have to be serialized does it? i have this function working well on another project but i cant figure out why this doesn't work.

You aren't returning the data in a data structure that jQuery knows how to parse. data will be a string so it won't have the properties you are trying to read.

You should use JSON instead.

Since you are making the request to a PHP script, do it like this:

header("Content-Type: application/json");
print json_encode(Array(
    "fname" => "test_fname",
    "lname" => "test_lname",
    "role" => "1"
));

Using dataType: "json" works, I don't know how I forgot it.

Based on your comment below the question about the response, it's not entirely clear what the exact content of data is but perhaps the json has not been parsed yet.

You can do that automatically using the dataType:

jQuery.ajax({
    type: "POST", // HTTP method POST or GET
    url: 'inc/functions.php?func=get_usr&id='+usr, //Where to make Ajax calls
    // here
    dataType: 'json',
    success:function(data){
        if (data.fname) {
         var fname = data.fname;
         //alert (fname);
        $('#rname').text(fname);
        }
     },
    error:function (xhr, ajaxOptions, thrownError){
       alert(thrownError);
    }
    });

adding dataType: "json" seemed to fix the issue, it wasn't until i happened to rescan the code to see that i had remmed it out.