問題描述
我想做的是通過 ajax 和 php 調(diào)用一些數(shù)據(jù)庫數(shù)據(jù).但是ajax調(diào)用不起作用,網(wǎng)上也找不到解決辦法.
What I'm trying to do is calling some database data via ajax and php. But the ajax call doesn't work, and I can't find out a solution on the web.
這是我的代碼:
test.php
<?php
include_once 'db_class.php';
$cat = $_GET['cat'];
$dbconn = new dbconn('localhost', 'root', 'somepsw', 'blog');
$dbconn->set_query("select * from posts where category = '".$cat."'");
echo '<br/>'.$dbconn->query.'<br/>';
$result = $dbconn->result;
$num = $dbconn->num_results;
$array = mysqli_fetch_assoc($result);
echo json_encode($array);
?>
如果我在瀏覽器上輸入那個(gè)網(wǎng)址:http://127.0.0.1:82/blog/ws/test.php?cat=css
If i type that url on browser: http://127.0.0.1:82/blog/ws/test.php?cat=css
jsonEncode 返回的數(shù)據(jù)是正確的,但是當(dāng)我用 jquery 在 html 頁面上加載它時(shí),他無法讀取數(shù)據(jù).
The data returned via jsonEncode is correct, but when i'm loading it on a html page with jquery he can't read the data.
test.html
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script>
function ajaxCall() {
var css;
$.ajax({
url: 'test.php',
type: "GET",
data: {cat: css},
dataType: 'json',
success: function(rows)
{
alert(rows);
},
error: function() { alert("An error occurred."); }
});
}
ajaxCall();
</script>
</head>
<body></body>
</html>
提前致謝.
推薦答案
你的變量 css
沒有價(jià)值.您想使用 string 'css'
.也許您也希望能夠加載其他類別.因此,將您的 ajaxCall
函數(shù)更改為
Your variable css
has no value. You wanted to use the string 'css'
. Maybe you want to be able to load other categories, too. So change your ajaxCall
function to
function ajaxCall(category)
{
$.ajax({
url: 'test.php',
type: "GET",
data: {cat: category},
dataType: 'json',
success: function(rows) {
alert(rows);
},
error: function() {
alert("An error occurred.");
}
});
}
并使用
ajaxCall('css');
這篇關(guān)于通過ajax調(diào)用加載mysqli php數(shù)據(jù)的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!