结束我的悲伤。
我向该文件发出 ajax 请求。
我想从数据库中获取所有帖子。然后风格化这些帖子并将其显示给用户。
但我不知道如何从 js 中解析这些。
...
$result = $conn->query($sql);
//Iterate the rows
while($row = $result->fetch_assoc())
{
//todo
}
...
//jsfile
...
var response = this.responseText;
//get the response but how to parse ?
最佳答案
From your Post, you sound like you want to send some Data obtained from your Database Transactions to the Requesting AJAX Script, right? If that is the case; you may have to do all the usual Processing of your DB Data and (if necessary) build them up as an Array or Object within your PHP File. Afterwards, you encode the resulting Data to JSON using
json_encode()
and then lastly push the JSON-Encoded Data back to the requesting AJAX Script. To illustrate; here (below) is a Mock example using bits & pieces of the Code you posted:
<?php
// PERFORM SOME DATABASE TRANSACTIONS....
$result = $conn->query($sql);
// IF YOU NEED TO BUILD-UP A SPECIAL DATA STRUCTURE TO MEET WITH
// THE NEEDS OF YOUR APP. YOU MIGHT DO THAT HERE.
// WE CREATE AN ARBITRARY ARRAY: $payload TO HOLD THE ARBITRARY DATA...
$payload = [];
// LOOP THROUGH THE RETURNED RESULT-SET / ROWS OF DATA
while($row = $result->fetch_assoc()) {
// WE PRETEND FOR NOW THAT WE NEED CERTAIN VALUES FOR THE APP
// THAT WILL BE CONSUMED BY THE REQUESTING AJAX SCRIPT
// SO WE BUILD IT HERE:
$tempData = []; //<== TEMPORARY ARRAY TO HOLD A COLLECTION
$tempData[] = $row['firs_name'];
$tempData[] = $row['last_name'];
$tempData[] = $row['address'];
$tempData[] = $row['email'];
$tempData[] = $row['avatar'];
$tempData[] = $row['telephone'];
// NOW PUSH THE COLLECTION OF RELEVANT DATA GATHERED
// FROM THE ITERATION INTO THE PAYLOAD VARIABLE: $payload
$payload[] = $tempData;
}
// OK: WE HAVE OUR PAYLOAD, READY TO BE SENT BACK AS JSON...
// SO WE NOW ENCODE THE PAYLOAD TO JSON DATA STRUCTURE.
$jsonData = json_encode($payload);
// THAT'S ALMOST IT....
// THE NEXT THING WOULD BE TO SHIP THESE DATA TO THE REQUESTING SCRIPT
// WHICH WE SHALL DO HERE WITH A SIMPLY die() STATEMENT LIKE SO:
die($jsonData);
关于javascript - 如何解析sql结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41202238/