gpt4 book ai didi

javascript - 从 mysql 和 php 检索 json 数据到 jquery

转载 作者:行者123 更新时间:2023-11-29 19:10:47 24 4
gpt4 key购买 nike

我正在尝试使用php将mysql数据导入jquery,我将数据转换成这样的JSON格式。

{"uid":"33","title":"Apple, Peach, Grapefruit","ing1":"apple","qty1":"1","meas1":"whole","ing2":"peaches \/ halved and","qty2":"2","meas2":"each","ing3":"grapefruit \/ peeled","qty3":"2","meas3":"each","ing4":"","qty4":"0","meas4":"each","ing5":"","qty5":"0","meas5":"each","ing6":"","qty6":"0","meas6":"each","ing7":"","qty7":"0","meas7":"each","ing8":"","qty8":"0","meas8":"each","ing9":"","qty9":"0","meas9":"each","ing10":"","qty10":"0","meas10":"each","servings":"2","benefits":""}

使用以下代码:

require_once'connect.php'; 
$uid = $_GET['uid'];
$sql = "SELECT * FROM recipes WHERE uid = '$uid'";
$result = mysqli_query($conn, $sql);

$num_rows = mysqli_affected_rows($conn);
while($row = mysqli_fetch_assoc($result)) {
$data = json_encode($row);
echo $data;
}

我正在使用 jquery .get 通过此代码将其拉入网页。

$(document).ready(function(e) {
var id = location.search;
uid=id.substring(4);
$.get('../jqm_juicing/data/get_json.php?uid=' + uid,function(data, status){
$("#display").append(data);
});
});

它显示的json数据如上。我希望能够单独访问不同的元素,我该怎么做?

最佳答案

如果你用 <script> 包裹它标签,并将其声明为变量,您就会拥有它。

require_once'connect.php'; 
$uid = $_GET['uid'];
$sql = "SELECT * FROM recipes WHERE uid = '$uid'";
$result = mysqli_query($conn, $sql);

$num_rows = mysqli_affected_rows($conn);

echo "<script>";
while($row = mysqli_fetch_assoc($result)) {
$data = json_encode($row);
echo "var myJson=" . $data;
}
echo "</script>";

现在,在主页脚本中,您可以像访问任何其他普通 JSON 一样访问此 JSON。
您可以将以下间隔放置在主页脚本中的任意位置:
这只是为了测试一下;)

var checkJson = setInterval(function(){

if(typeof(myJson.uid)!="undefined"){

clearInterval(checkJson);

console.log("myJson uid: " + myJson.uid);
console.log("myJson title: " + myJson.title);
// etc...

}else{
console.log("JSON not loaded yet.");
}

},500);

关于javascript - 从 mysql 和 php 检索 json 数据到 jquery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43099628/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com