Ajax响应未定义如何解决?

时间:2017-04-18 09:59:58

标签: jquery ajax

Json数据:

4

当我调用ajax函数时,我得到了这个响应。但当我警告[{"id":"1","reg_title":"Mr.","reg_first_name":"shah","reg_last_name":"rushabh","reg_email":"shahrushabh1996@gmail.com","reg_password":"$2y$15$tPAtKlT6VPtmPFRvlIuA0.Xh1IGh\/1.FY09lFXOrzrv3UkrJOFHna","fbid":"","secret_question":"","secret_answer":"","company":"","work_phone_number":"","home_phone_number":"","mobile_phone_number":"","reg_address":"b\/1 rajasthan Flat","reg_no":"123","reg_country":"India","reg_postal":"380005","reg_city":"Ahmedabad","reg_state":null,"reg_gender":"Male","reg_verifycode":"899884070","reg_active":"Yes","type":"","token":"","image":"","reg_voucher":"","reg_date":"2017-04-18","user_lat":"","user_long":"","newsletteractive":"","showtel":"No","website":""}] 显示未定义时,请帮助我。如何显示数据?

3 个答案:

答案 0 :(得分:1)

检查您获得的回复类型。您获得的响应采用 JSON字符串格式。当您得到除JSON之外的响应时,您必须将响应解析为JSON。

 response = JSON.parse(response);

然后,您可以访问所需的响应[index] .property

答案 1 :(得分:0)

因为您的回复是一个数组,所以您必须告诉javascript您要访问的数组中的哪个项目。

所以而不是

response.id

你必须做这样的事情

response[0].id

更新



var response = [{"id":"1","reg_title":"Mr.","reg_first_name":"shah","reg_last_name":"rushabh","reg_email":"shahrushabh1996@gmail.com","reg_password":"$2y$15$tPAtKlT6VPtmPFRvlIuA0.Xh1IGh\/1.FY09lFXOrzrv3UkrJOFHna","fbid":"","secret_question":"","secret_answer":"","company":"","work_phone_number":"","home_phone_number":"","mobile_phone_number":"","reg_address":"b\/1 rajasthan  Flat","reg_no":"123","reg_country":"India","reg_postal":"380005","reg_city":"Ahmedabad","reg_state":null,"reg_gender":"Male","reg_verifycode":"899884070","reg_active":"Yes","type":"","token":"","image":"","reg_voucher":"","reg_date":"2017-04-18","user_lat":"","user_long":"","newsletteractive":"","showtel":"No","website":""}];

console.log('id:', response[0].id)
console.log('reg_last_name:', response[0].reg_last_name)
console.log('reg_no:', response[0].reg_no)




答案 2 :(得分:0)

因为您正在使用ajax服务,所以您的响应将采用对象格式。您需要使用将其转换为JSON格式 var response= $.parseJSON(request);

然后您可以通过将此json变量放入for循环来检索其数据,如下面的代码所示。它将打印所有记录数据

var response = [{"id":"1","reg_title":"Mr.","reg_first_name":"shah","reg_last_name":"rushabh","reg_email":"shahrushabh1996@gmail.com","reg_password":"$2y$15$tPAtKlT6VPtmPFRvlIuA0.Xh1IGh\/1.FY09lFXOrzrv3UkrJOFHna","fbid":"","secret_question":"","secret_answer":"","company":"","work_phone_number":"","home_phone_number":"","mobile_phone_number":"","reg_address":"b\/1 rajasthan  Flat","reg_no":"123","reg_country":"India","reg_postal":"380005","reg_city":"Ahmedabad","reg_state":null,"reg_gender":"Male","reg_verifycode":"899884070","reg_active":"Yes","type":"","token":"","image":"","reg_voucher":"","reg_date":"2017-04-18","user_lat":"","user_long":"","newsletteractive":"","showtel":"No","website":""}];

for(i=0;i<response.length;i++)
{
console.log('id:', response[i].id+'  && reg_last_name:', response[i].reg_last_name+'  && reg_no:', response[i].reg_no);

}