简体   繁体   中英

Javascript, Cannot read property of undefined, but prints to console

在此输入图像描述 I have a jQuery call which is getting the data in to a object. I'm trying to use the object value to set as a label text from javascript , but it throws

"Cannot read property '0' of undefined."

where as it prints the value successfully to the console.

 var questionData; var optionData; $(document).ready(function () { $.ajax({ url: 'coaching-assessment-tool.aspx/GetCATQuestionAndOptions', type: 'POST', dataType: 'json', contentType: "application/json; charset=utf-8", success: function (data) { questionData = data.d[0]; optionData = data.d[1]; console.log(questionData[0].QuestionText); console.log("Question Data", questionData); console.log("Option Data", optionData); }, error: function (error) { console.log(error); alert('Error retrieving data. Please contact support.'); } }); document.getElementById('firstQuestion').innerHTML = questionData[0].QuestionText; }); 

I need the label text as the object value (questionData[0].QuestionText). 在此输入图像描述

$.ajax() is asynchronous by default , so setting innerHTML is happening before questionData is populated. Move line 22 inside the success callback to make sure the data is available before it is used.

While it's technically possible to make the call synchronous, it's a bad idea.

$.ajax({
   // ...
   async: false,
   // ...
});

That code would prevent any other JavaScript from executing until the ajax call is complete.

Just as an aside, some JavaScript tooling like TypeScript can help you catch those mistakes before the code executes in a browser. I've recently converted some JS to TS and been very happy with the number of bugs I've caught.

Cheers!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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