AJAX调用过多

时间:2019-02-10 11:22:03

标签: php mysql ajax

我的代码太乱了。每次显示元素时,我都会创建1个Ajax调用。我的表格将有80行的固定数目。如何简化重复的AJAX调用。

HTML

<tr>
<td>
    <div class="form-group row mb-0" >
        <div class="col-12">
            <select class="form-control form-control-sm mySelect2 " name="111" id="111">
                <?php
                include ('server_side/connection.php');
                $sql = "SELECT * FROM tbl_subjects";
                $result=mysqli_query($conn, $sql);
                while ($row=mysqli_fetch_array($result)) { ?>
                <option value="<?php echo $row['subject_code'];?>"><?php echo $row['subject_code'];?></option>
                <?php } ?>
            </select>
        </div>
    </div>
</td>
<td><span id="description_111"></span></td>
<td><span id="prerequisite_111"></span></td>
<td><span id="unit_111"></span></td>

AJAX

$("#111").change(function(){
        var subject_code = $(this).val();
        $.ajax({
            type: "POST",
            url: "server_side/load_subjectdesc.php",
            data: {subject_code: subject_code},
            success: function(result){
            $("#description_111").html(result);
            }
        });
    });
    $("#111").change(function(){
        var subject_code = $(this).val();
        $.ajax({
            type: "POST",
            url: "server_side/load_subjectpreq.php",
            data: {subject_code: subject_code},
            success: function(result){
            $("#prerequisite_111").html(result);
            }
        });
    });
    $("#111").change(function(){
        var subject_code = $(this).val();
        $.ajax({
            type: "POST",
            url: "server_side/load_subjectunit.php",
            data: {subject_code: subject_code},
            success: function(result){
            $("#unit_111").html(result);
            }
        });
    });

每显示一个项目一个Ajax太多。如何简化或删除这么多AJAX调用?

1 个答案:

答案 0 :(得分:1)

您将需要创建一个php页面,该页面将返回以下形式的JSON:

{
    description: 'descriptionvalue',
    perequisite: 'perequisitevalue',
    unit: 'unitvalue'
}

,您将向其发送AJAX请求,例如:

$("#111").change(function(){
    var subject_code = $(this).val();
    $.ajax({
        type: "POST",
        url: "server_side/yourpage.php",
        data: {subject_code: subject_code},
        success: function(result){
            for (var key in result) $("#" + key + "_111").html(result[key]);
        }
    });
});

您可以进一步完善:

function myChange(idVal) {
    $("#" + idVal).change(function(){
        var subject_code = $(this).val();
        $.ajax({
            type: "POST",
            url: "server_side/yourpage.php",
            data: {subject_code: subject_code},
            success: function(result){
                for (var key in result) $("#" + key + "_" + idVal).html(result[key]);
            }
        });
    });
}