weixin_33674976 2014-11-22 19:57 采纳率: 0%
浏览 31

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.

  • 写回答

4条回答 默认 最新

  • weixin_33682790 2014-11-22 20:03
    关注

    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"
    ));
    
    评论

报告相同问题?