[英]How to read data from json array in jquery?
我必須從MySQL檢索許多行並通過用ajax編碼發送,而我做到了。 但問題是我無法在ajax中處理輸出數組數據。 有人可以幫我嗎?
1> one.php
<?php
$host = "localhost";
$user = "root";
$pass = "";
$databaseName = "elearning";
$tableName = "users";
$con = mysql_connect($host,$user,$pass);
$dbs = mysql_select_db($databaseName, $con);
if(isset($_POST)){
$exam_id=$_POST['exam_id'];
$sql="select * from exam_to_question where exam_id=$exam_id";
$result = mysql_query($sql);
$dataArray = array();
while($array = mysql_fetch_assoc($result)){
$dataArray[] = $array;
}
echo json_encode($dataArray);
}
?>
2>和ajax代碼是:
$.ajax({
type: 'POST',
url: '../functions/one.php',
data: "exam_id="+exam_id,
dataType: 'json',
success: function(data){
//alert(data[0]['question_id']);
// i have to handle data here
},
error:function(){
alert("AJAX failure");
}
});
如果這是一個數組,則必須使用jQuery的.each()
方法:
$.each(data, function(i, resp){
console.log(resp);
});
您將獲得帶有ajax響應的jquery對象。 因此,您可以使用以下任何功能對其進行處理: http : //api.jquery.com/each/ http://api.jquery.com/jQuery.each/
如果您使用過dataType:json,則可以直接使用
//if it is not a multidimensional array then you can dirctly
data.keyName
//if it is multidimensional array
$(data).each(function(index,element){
console.log(element);
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.