简体   繁体   English

来自ajax中JSON响应的值返回未定义

[英]Values from a JSON response in ajax returning as undefined

I'm having some problems when trying to retrieve values from a JSON response sent via the $.post() method in jQuery. 尝试从通过jQuery中的$.post()方法发送的JSON响应中检索值时遇到一些问题。 Here is the script: 这是脚本:

var clickedName = $('#customerId').val();

$.post("/customer-search", { name: clickedName }).done( function(response) {
    var results = $.parseJSON(response);    
    console.log(results);

    $('#account-name').html(results.firstname + ' ' + results.lastname);
    $('#email').html(results.email);
    $('#telephone').html(results.telephone);
    if (results.fax) {
        $('#fax').html(results.fax);
    } else {
        $('#fax').html('n/a');
    }
    $('#personal').fadeIn();
    return false;
});

Just to explain, I'm using twitter typeahead in a Symfony2 project, and basically this script will fire when a name is clicked (selected) from the list after typing. 只是为了说明一下,我在Symfony2项目中使用了Twitter typeahead,基本上,当键入后从列表中单击(选择)名称时,此脚本将触发。 The customer-search URL runs a search of the database as follows: 客户搜索URL如下运行数据库搜索:

$q = $request->request->get('name');
$em = $this->getDoctrine()->getManager();
$customer = $em->getRepository('AppBundle:Oc73Customer')->findLikeName($q);
$addresses = $em->getRepository('AppBundle:Oc73Address')->findByCustomerId($customer[0]['customerId']);

$results = array();
$results['customer'] = $customer;
$results['addresses'] = $addresses;

return new Response(json_encode($results));

Which will successfully return a Json encoded response, and the value of 'response' which is printed in the console (as per the jquery above) is: 它将成功返回Json编码的响应,并且在控制台中打印的“ response”值(根据上述jquery)为:

{
    "customer": [{
        "firstname": "Mike",
        "lastname": "Emerson",
        "email": "xxxx@xxxx.co.uk",
        "telephone": "01234 5678910",
        "fax": null,
        "password": "8e1f951c310af4c20e2cd6b68dee506ac685d7ae",
        "salt": "e2b9e6ced",
        "cart": null,
        "wishlist": null,
        "newsletter": 0,
        "addressId": 84,
        "customerGroupId": 1,
        "ip": null,
        "status": 1,
        "approved": 1,
        "token": null,
        "dateAdded": {
            "date": "2016-02-16 12:59:28.000000",
            "timezone_type": 3,
            "timezone": "Europe/Berlin"
        },
        "availCredit": null,
        "customerId": 75
    }],
    "addresses": [{}]
}

I am trying to retrieve the customer details by using the method I always use, so to get the firstname, I use results.firstname where results is a parsed JSON string, as written in my jQuery response. 我试图通过使用我经常使用的方法来检索客户详细信息,因此要获取名字,我使用results.firstname ,其中results是解析的JSON字符串,如我的jQuery响应中所述。

However, all I get from results.firstname is undefined , even when it clearly is defined. 但是,我从results.firstname获得的所有内容都是undefined ,即使明确定义了它也是如此。 So, basically, I'm wondering what I am doing wrong? 所以,基本上,我想知道我做错了什么?

Hope someone can shed some light on my problem. 希望有人可以阐明我的问题。

The properties you're trying to access are objects in the customer array, not on the parent object itself. 您尝试访问的属性是customer数组中的对象,而不是父对象本身。 Assuming that the response only ever contains one customer object then you can use result.customer[0] , like this: 假设响应仅包含一个客户对象,则可以使用result.customer[0] ,如下所示:

$.post("/customer-search", { name: clickedName }).done(function(response) {
    var results = $.parseJSON(response);
    var customer = response.customer[0];

    $('#account-name').html(customer.firstname + ' ' + customer.lastname);
    $('#email').html(customer.email);
    $('#telephone').html(customer.telephone);
    $('#fax').html(customer.fax ? customer.fax : 'n/a');
    $('#personal').fadeIn();
});

If it's possible that multiple customer objects will be returned in the array the you would need to amend your code to loop through those objects and build the HTML to display them all - without using id attributes. 如果有可能在数组中返回多个customer对象,则需要修改代码以遍历这些对象并构建HTML以显示所有对象,而无需使用id属性。

I was able to access it like "results.customer[0].firstname" 我可以像“ results.customer [0] .firstname”一样访问它

var cus = 
    {
    "customer": [{
        "firstname": "Mike",
        "lastname": "Emerson",
        "email": "xxxx@xxxx.co.uk",
        "telephone": "01234 5678910",
        "fax": null,
        "password": "8e1f951c310af4c20e2cd6b68dee506ac685d7ae",
        "salt": "e2b9e6ced",
        "cart": null,
        "wishlist": null,
        "newsletter": 0,
        "addressId": 84,
        "customerGroupId": 1,
        "ip": null,
        "status": 1,
        "approved": 1,
        "token": null,
        "dateAdded": {
            "date": "2016-02-16 12:59:28.000000",
            "timezone_type": 3,
            "timezone": "Europe/Berlin"
        },
        "availCredit": null,
        "customerId": 75
    }],
    "addresses": [{}]
}
    alert(cus.customer[0].firstname);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM