在ajax下使用每个循环时出错

Getting error while using each loop under ajax

本文关键字:循环 出错 ajax      更新时间:2023-09-26

当我在Ajax调用下尝试每个循环时,我得到的错误为:

TypeError: invalid 'in' operand e

下面是我的Ajax调用代码

    $.ajax({
        type: "POST",
        url: "/admin/counselormanagement/centername",
        data: 'groupId='+valueSelected,
        async: true,
        success: function(arrCenter) {
            $.each(arrCenter, function( intValue, arrValue ) {
                console.log('<option value="' + arrValue['ID'] + '">'+ arrValue['CenterName'] +'</option>');
            });
        }
    });

我从服务器得到的回复是:

Array (
[0] => Array
    (
        [ID] => 4
        [CenterName] => test2
        [ParentName] => 2
        [Parent] => 3
        [GroupName] => test
        [Type] => 1
    )
[1] => Array
    (
        [ID] => 8
        [CenterName] => test21
        [ParentName] => 2
        [Parent] => 3
        [GroupName] => test
        [Type] => 1
    )
 )

我使用PHP作为后端,其代码为:

$arrCenterName   = array();
$objCenterMapper = new Application_Model_CentersMapper();
$arrCenter = $objCenterMapper->seekCenters($_POST['groupId']);
print_r($arrCenter[0]);
die();

在PHP中使用json_encode()返回响应。你的JS代码应该是这样的:

PHP:

$arrCenterName   = array();
$objCenterMapper = new Application_Model_CentersMapper();
$arrCenter = $objCenterMapper->seekCenters($_POST['groupId']);
echo json_encode($arrCenter[0]);
die();

JQuery:

$.ajax({
    type: "POST",
    url: "/admin/counselormanagement/centername",
    data: 'groupId='+valueSelected, 
    dataType: 'json', 
    async: true,
    success: function(arrCenter) {
        $.each(arrCenter, function( intValue, arrValue ) {
            console.log('<option value="' + arrValue.ID + '">'+ arrValue.CenterName +'</option>');
        });
    }
});

尝试使用json_encode来回显对象:

<?php
$arrCenterName   = array();
$objCenterMapper = new Application_Model_CentersMapper();
$arrCenter = $objCenterMapper->seekCenters($_POST['groupId']);
echo json_encode($arrCenter[0]);
die();