我试图通过使用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数据。我希望能够单独访问不同的元素,我该怎么做?
答案 0 :(得分:0)
在jQuery中,在追加(数据)之前添加JSON.parse()。
$(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(JSON.parse(data));
});
});
我刚刚更改了这一行:
$("#display").append(JSON.parse(data));
希望这有帮助!
答案 1 :(得分:0)
如果用<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);
答案 2 :(得分:0)
检索json数据以使用json response jquery parse函数。使用此函数的json数据 jQuery.parseJSON()