我有我的當前web應用程序項目顯示一個簡單的jpg圖片的麻煩,基於什麼單選按鈕檢查使用jquery ajax與php腳本與mysql通信。麻煩使用jquery Ajax和php腳本從mysql中檢索數據
這裏是我的ajax.js文件:
$('#selection').change(function() {
var selected_value = $("input[name='kobegreat']:checked").val();
$.ajax({
url: "kobegreat.php",
data: {"name": selected_value},
type: "GET",
dataType: "json",
success: function(json) {
var $imgEl = $("img");
if($imgEl.length === 0) {
$imgEl = $(document.createElement("img"));
$imgEl.insertAfter('h3');
$imgEl.attr("width", "300px");
$imgEl.attr("alt", "kobepic");
}
$imgEl.attr('src', json["link"]);
alert("AJAX was a success");
},
cache: false
});
});
而且我kobegreat.php文件:
<?php
$db_user = 'test';
$db_pass = 'test1';
if($_SERVER['REQUEST_METHOD'] == "GET") {
$value = filter_input(INPUT_GET, "name");
}
try {
$conn = new PDO('mysql: host=localhost; dbname=kobe', $db_user, $db_pass);
$conn->setAttribute(PDO:: ATTR_ERRMODE, PDO:: ERRMODE_EXCEPTION);
$stmt = $conn->prepare('SELECT * FROM greatshots WHERE name = :name');
do_search($stmt, $value);
} catch (PDOException $e) {
echo 'ERROR', $e->getMessage();
}
function do_search ($stmt, $name) {
$stmt->execute(['name'=>$name]);
if($row = $stmt->fetch()) {
$return = $row;
echo json_encode($return);
} else {
echo '<p>No match found</p>;
}
}
?>
HTML代碼,我想顯示我的圖像:
<h2>Select a Great Kobe Moment.</h2>
<form id="selection" method="get">
<input type="radio" name="kobegreat" value="kobe1" checked/>Kobe1
<input type="radio" name="kobegreat" value="kobe2"/>Kobe2
<input type="radio" name="kobegreat" value="kobe3"/>Kobe3
</form>
<div id="target">
<h3>Great Kobe Moment!</h3>
</div>
最後我的數據庫是這樣設置的:
greatshots(name, link)
name link
------ --------
kobe1 images/kobe1
kobe2 images/kobe2
kobe3 images/kobe3
我知道PHP腳本成功地從數據庫中抓取的寫入數據,因爲所有的目標DIV下顯示是這樣的:
{"name":"kobe3","0":"kobe3","link":"images\/kobe3","1":"images\/kobe3"}
而且我知道AJAX函數返回成功,因爲當我選擇一個單選按鈕時,成功的ajax請求警報會提醒我。所以我不確定我要出錯的地方或如何解決我的問題。
這是我從複製代碼複製的錯誤,假設是函數(json),但json.link也不起作用。 – Scott