[英]how to fetch the array data from database query in a php file to ajax sucess data
我試圖獲取數組中的數據,從SQL查詢到ajax成功數據。 這是我試過的代碼,
function adminchecksub(value1){
//alert('hi');
var value1=$('#adminsid').val();
//alert(value1);
if(value1==''){
alert('Please enter a Sub id');
}
else{
//alert(value1);
$.ajax({
type: 'POST',
url: root_url + '/services/services.php?method=adminsubcheck',
data: {value1:value1},
async: true,
success: function (data) {
alert(data);
if (data == 1) {
alert('inside');
//window.location.assign(rdurl+"?sid="+sid);
return true;
} else {
//alert('does not exist!');
//alert('outside');
return false;
}
}
});
}
現在在從上面的ajax調用請求的php方法中,我必須通過這個返回數組的函數返回數據
function adminsubcheck($sid){
$subid=$sid['value1'];
$row = array();
//echo $subid;
$query = "SELECT Sub_id,Status,Sub_type FROM Sub WHERE Sub_id=$subid";
//echo $query;
//echo $subid;
$queryresult = mysql_query($query);
$count = mysql_num_rows($queryresult);
//echo $count;
while ($r = mysql_fetch_assoc($queryresult)) {
$row[] = $r;
}
return $row;
}
這里$ row將一個數組作為數據返回給ajax函數,我需要單獨獲取所有項目。 有人幫助我將值輸入ajax調用。 提前致謝..
return $row;
像這樣替換
echo json_encode($row);
並在像這樣的ajax中添加dataType ='json'
dataType: 'json',
如果你想在ajax調用中獲取值,我認為它應該是:
while ($r = mysql_fetch_assoc($queryresult)) {
$row[] = $r;
}
echo json_encode(array('data'=>$row));
exit;
在PHP文件中,您可以通過以下方式將數組作為json對象返回(請注意PHP文件如何回顯結果以將其傳遞回javascript)
...
$json = json_encode($row);
echo $json
現在將以下內容添加到您的javascrip ajax中
$.ajax({
...
// Whatever code you currently have
...
}).done(function ( json ) {
var data = JSON.parse(json);
//Continue with javascript
});
您可以像在PHP中一樣將java腳本變量'data'作為關聯數組來處理
另外,看看如何填充php變量$ row並調整以下方式:
$cnt = 0;
while ($r = mysql_fetch_assoc($queryresult)) {
$row[$cnt] = $r;
$cnt++;
}
$json = json_encode($row);
echo $json;
在javascript中,您可以通過以下方式在數據變量中訪問您的行:
var value = data[0]['field_name'];
在上面的語句中,0將對應$ cnt的值(即mysql返回的行號)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.