嘿伙计们,我试图通过 json_encode 获取我的 ajax 的值并使用 $.each 来迭代每个结果,但是每个输入都从我的 php 返回未定义的值这里是 ajax
var counter_sub = 0 ;
var html;
$.ajax({
type:'POST',
url:'add_subject.php',
dataType:'json',
data:{'func_numbr':'2'},
success:function (data){
$.each(data, function(i, item) {
html = "<tr>";
html += "<td><lable>Subject: </label><input type='text' name='subject["+counter_sub+"]' value='"+data[i].subj_name+"'></td>";
html += "<td><input type='button' id='activate' name='active' class='button' value='Active'> ";
html += "<input type='button' id='inactivate' name='active' class='button' value='Inactive'></td>";
html += "</tr>";
$('#curr-elem-tble').append(html);
counter_sub = counter_sub +1;
});
}
});
和PHP
<?php
include_once('DBconnect.php');
$func_num = $_POST['func_numbr'];
switch ($func_num) {
case 1:
insert_new_subject();
break;
case 2:
get_elementary_subjects();
break;
}
function insert_new_subject(){
$level = $_POST['year_level'];
$subjct_name =$_POST['subjct_name'];
$units_nmber = $_POST['subjct_units'];
$insert_subject = "INSERT INTO subjects (subject_name,level,status,subject_units) VALUES('$subjct_name','$level','1','$units_nmber')";
if(@!mysql_query($insert_subject)){
die('error insert'.mysql_error());
}
else{
$return ['error'] = false;
}
echo json_encode($return);
}
function get_elementary_subjects(){
$select_subjects_elem = "SELECT subject_name,subject_id,status FROM subjects WHERE level='elementary' ";
$connect = mysql_query($select_subjects_elem) or die(mysql_error());
$data[]=array();
while($row = mysql_fetch_array($connect)){
$data= array(
'subj_name' =>$row['subject_name'],
'subj_id'=>$row['subject_id'],
'subj_status'=>$row['status'],
);
}
echo json_encode($data);
}
?>
我将每个 td 切成不同的 html 行并用 += 连接它仍然无法弄清楚为什么它返回未定义。我用firebug检查了它,控制台只返回1行数据,尽管它遍历所有结果。