【问题标题】:foreach function in JSON returning only one rowJSON中的foreach函数只返回一行
【发布时间】:2018-08-17 11:38:05
【问题描述】:

我试图从 JSON 响应中显示不止一行,但不知何故它每次只返回一行。查询在服务器上运行良好。如果我在没有 ajax/json 的情况下使用它,代码效果很好。我为此头疼。我在这里做错了什么?任何帮助,将不胜感激。

HTML

         <form>
              <span id="span_section_row"></span>
                    <hr>
                    <div class="row">
                        <div class="form-group col-lg-6">
                            <label for="exam_date">Select Date of Exam</label>
                            <input type="text" class="form-control" id="exam_date" required readonly>
                        </div>
                        <div class="form-group col-lg-6">
                            <label for="exam_time">Enter Exam Time(In Minutes)</label>
                            <input type="number" class="form-control" id="exam_time" required>
                        </div>
                    </div>
                </form>

AJAX 调用:

$(document).on('click', '.schedule', function(){
        var exam_id = $(this).attr("id");
        var btn_action = 'fetch_single';
        $.ajax({
            url:'web-services/schedule-exam.php',
            method:"POST",
            data:{exam_id:exam_id, btn_action:btn_action},
            dataType:"json",
            success:function(data)
            {
                $('#setup_exam_modal').modal('show');
                $('#span_section_row').html(data.section_row);
            }
        })
    });

PHP:

if($_POST['btn_action'] == 'fetch_single')
    {
        $exam_type_id = $_POST['exam_id'];
        $query = "
        SELECT a.*, b.exam_type_name 
                        FROM exam_section a
                        INNER JOIN exam_type b 
                        ON a.exam_type_id=b.exam_type_id
                         WHERE a.status = :status
                         AND a.exam_type_id = :exam_type_id
        ";
        $statement = $conn->prepare($query);
        $statement->execute(
            array(
                ':status'    =>    'active',
                ':exam_type_id'    =>    $exam_type_id

            )
        );
        $result = $statement->fetchAll();
        foreach($result as $row)
        {
            $output['section_id'] = $row['section_id'];
            $output['exam_type_id'] = $row['exam_type_id'];
            $output['section_name'] = $row['section_name'];
            $output['exam_type_name'] = $row['exam_type_name'];

            $output['section_row'] = 
                                '<div class="row">
                                <div class="form-group col-lg-4">
                                    <label for="select_section"></label>
                                    <p id="select_section">'.$row['section_name'].'</p>
                                </div>
                                <div class="form-group col-lg-4">
                                    <label for="no_of_questions">No. of Questions</label>
                                    <input type="number" class="form-control" id="no_of_questions" required>
                                </div>
                                <div class="form-group col-lg-4">
                                    <label for="mark_per_question">Mark Per Question</label>
                                    <input type="number" class="form-control" id="mark_per_question" required>
                                </div>
                            </div>
                            ';
        }
        echo json_encode($output);
    } 

【问题讨论】:

  • 你在每次循环中都会覆盖相同的键。因此,您在第一个循环中保存的值只会在第二个循环中被覆盖。
  • 感谢您的解释,但我该如何克服这个问题
  • 输入字段可以是requiredreadonly 吗? &lt;input type="text" class="form-control" id="exam_date" required readonly&gt; 对我来说似乎没有多大意义
  • @RiggsFolly 是的,这是必填字段,单击时显示日历,用户无法从键盘输入。

标签: php jquery json ajax


【解决方案1】:

首先在 PHP 中,您在每次循环时都会覆盖数组,因此只会有一个事件被传回 javascript 进行处理

if($_POST['btn_action'] == 'fetch_single') {
    $exam_type_id = $_POST['exam_id'];
    $query = "SELECT a.*, b.exam_type_name 
              FROM exam_section a
                INNER JOIN exam_type b ON a.exam_type_id=b.exam_type_id
              WHERE a.status = :status
              AND a.exam_type_id = :exam_type_id";

    $statement = $conn->prepare($query);
    $statement->execute(
            array(  ':status' => 'active', 
                    ':exam_type_id' => $exam_type_id)
                );
    $result = $statement->fetchAll();

    foreach($result as $row) {
        $htm = '<div class="row">
                    <div class="form-group col-lg-4">
                        <label for="select_section"></label>
                        <p id="select_section">'.$row['section_name'].'
                        </p>
                    </div>
                    <div class="form-group col-lg-4">
                        <label for="no_of_questions">No. of Questions</label>
                        <input type="number" class="form-control" id="no_of_questions" required>
                    </div>
                    <div class="form-group col-lg-4">
                        <label for="mark_per_question">Mark Per Question</label>
                        <input type="number" class="form-control" id="mark_per_question" required>
                    </div>
                </div>';

        $output[] = [
                    'section_id'        => $row['section_id'],
                    'exam_type_id'      => $row['exam_type_id'],
                    'section_name'      => $row['section_name'],
                    'exam_type_name'    => $row['exam_type_name'],
                    'section_row'       => $htm
                    ];
    }
    echo json_encode($output);
} 

所以现在在 javascript 中,您需要按照 RASHAN 的建议处理该数组

$(document).on('click', '.schedule', function(){
    var exam_id = $(this).attr("id");
    var btn_action = 'fetch_single';
    $.ajax({
        url:'web-services/schedule-exam.php',
        method:"POST",
        data:{exam_id:exam_id, btn_action:btn_action},
        dataType:"json",
        success:function(data)
        {
            $('#setup_exam_modal').modal('show');
            //$('#span_section_row').html(data.section_row);
            var t="";
            $.each(data,function(index,value){
               // concatenate all the occurances of the html and place on page
                t += value.section_row;
            })
            $('#span_section_row').html(t);
        }
    })
});

现在你还有一个我可以看到的问题,那就是你正在生成多个 HTML 元素,所有元素都使用相同的id,就像这里一样,

<p id="select_section">'.$row['section_name'].'

在 HTML 的多个部分中。由于我不熟悉代码中其他地方发生的事情,因此您可能根本不需要这些 id 并且可以删除它们。或者你必须让它们在页面上独一无二,或者修改你的 javascript 以其他方式选择这些元素

【讨论】:

  • 它就像一个魅力!你是一个储蓄者!是的,我需要生成多个 id,但这不是一个大问题,主要问题已经解决了。
【解决方案2】:

从您的控制器中,您将数据作为数组返回,您需要将响应迭代为

var append="";
$.each(data,function(i,v){
    append += v.section_row;
})
$('#span_section_row').html(append);

【讨论】:

  • 感谢您的回答,但显示未定义
  • @UpendraJoshi 显示位置
  • 在跨度区。
猜你喜欢
  • 2018-01-23
  • 1970-01-01
  • 2016-06-03
  • 2015-07-21
  • 2014-01-03
  • 2021-08-22
  • 1970-01-01
  • 2014-12-29
  • 2019-03-22
相关资源
最近更新 更多