【问题标题】:How do i access the objects inside the array returned by a javascript function如何访问由 javascript 函数返回的数组中的对象
【发布时间】:2017-04-13 19:42:52
【问题描述】:

这个函数调用一个响应 JSON 数据的 PHP 脚本,它遍历 JSON 对象,创建一个新对象并将这个新对象推送到函数返回的数组中

function getTestQuestions() {
        // alert('10');
        var sessionQuestions = [];
        $.getJSON('testservice.php?action=getQuestions', function(json){
            
            
            if (json.your_questions.length > 0) {
                var totalQuestions = json.your_questions.length;
                totalQuestions_global = totalQuestions;



                for (var i = 0; i < totalQuestions; i++) {

                    var question_object = new Object();
                    question_object.serialNo = i;
                    question_object.passage = json.your_questions[i]['passage'];
                    question_object.cur_question = json.your_questions[i]['question'];
                    question_object.option1= json.your_questions[i]['option1'];
                    question_object.option2 = json.your_questions[i]['option2'];
                    question_object.option3 = json.your_questions[i]['option3'];
 

                    sessionQuestions.push(question_object);

                }

            }
        });
        
        return sessionQuestions;
    }

下一个函数调用这个函数。但是我在访问数组内的对象时遇到问题。见代码:

function initialTestLoaded() {

                var allQuestions = getTestQuestions();                   

                $('.current_quest').text(allQuestions[0]['serialNo']);
                $('.total_quest').text(testQuestions.length);

最后两行代码返回无法访问未定义的“serialNo”ppty的错误。

这是我第一次在这里发布问题,我相信这里的好人会一如既往地提供很大帮助。谢谢

【问题讨论】:

  • no no,只需将json响应传递给php,然后使用json_decode($json, true)它会自动转换为数组。然后使用该数组访问数组中的元素。比如 $array['passage'] 等。
  • 这是因为$.getJSON 是一个异步函数,而getTestQuestions 函数永远不会等待结果,总是返回一个未定义的值。
  • 谢谢大家。在回显之前,我需要先在 php 中进行 json_decode 吗?大多数文章建议访问 json_encoded 对象,因为它在 javascript 中。我的挑战不是我无法在 javascript 中访问 json_encoded 对象,而是在遍历所有条目并将它们推送到一个函数中的数组之后,当我调用它时,我似乎无法访问这个返回数组的元素在另一个函数中起作用。在函数声明中运行 Console.log 显示该数组已正确填充,但在调用函数中显示未定义。请指导我。

标签: javascript php jquery arrays json


【解决方案1】:

在 php 中只需使用 json_decode

json_decode($jsondata, true);

基本示例

<?php 
$json_string = 'https://example.com/jsondata.json';
$jsondata = file_get_contents($json_string);
$obj = json_decode($jsondata,true);
echo "<pre>";
print_r($obj);
?>

【讨论】:

    猜你喜欢
    • 2013-06-07
    • 2020-01-31
    • 1970-01-01
    • 1970-01-01
    • 2011-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-23
    相关资源
    最近更新 更多