[英]How to fetch correct data from database with ajax
在我的項目中,我使用ajax從數據庫中獲取數據。 然后測試數據內容,在成功函數中選擇alert(valData)。 但是很不幸,ajax沒有任何回報。 我測試了
select contact from IDC WHERE id=5;
它在mysql cmd行中工作正常。
這是我的js代碼:
var stNum = 5;
$.ajax({
dataType:'json',
type:"POST",
url:"get_ajax_csc.php",
data:{stNum:stNum},
success:function(data)
{
var valData = data;
alert(valData);
}
});
這是get_ajax_csc.php代碼:
<?php
if(isset($_POST['stNum']))
{
include("DB.php");
$q=$_POST["stNum"];
$sql="select contact from IDC WHERE id='".$q."';";
$sel = $conn->query($sql);
$arr = $sel->fetch(PDO::FETCH_ASSOC);
echo $arr['contact'];
}
if(isset($_POST['htmlCnt']))
{
include("DB.php");
$htcnt=stripslashes(".$_POST['htmlCnt'].");
........
}
?>
這是DB.php代碼:
<?php
session_start();
$pwd=$_SESSION['password'];
$user=$_SESSION['user'];
try
{
$conn = new PDO('mysql:host=x.x.x.x;port=3306;dbname=hpc',$user,$pwd);
}
catch (PDOException $e)
{
echo "account or pwd wrong <meta http-equiv='refresh' content='1;url=index.html'>";
exit;
}
$conn->setAttribute(PDO::ATTR_ORACLE_NULLS, true);
?>
我的代碼似乎沒有錯,但是我無法從數據庫中獲取數據
我不知道該錯誤,誰可以幫助我?
從服務器發送回客戶端的數據不是有效的json數據,因為您在ajax中指定了期望json數據。
另外,您的查詢也不相同:
SELECT contact from IDC WHERE id=5; // This is the correct query you run on the cmd line.
$sql="select contact from IDC WHERE id='".$q."';"; // This is the one from your php
如果仔細查看查詢,第一個ID將被視為整數,第二個ID將被視為字符串。 請參閱何時在MySQL中使用單引號,雙引號和反引號
另外,您正在使用PDO,因此要充分利用使用預准備語句的優勢。 試試下面的代碼:
<?php
if (isset($_POST['stNum'])) {
include("DB.php");
$q = $_POST["stNum"];
$sql = "select contact from IDC WHERE id= ? ";
$sel = $conn->prepare($sql);
$sel->bindParam(1, $q, PDO::PARAM_INT);
$sel->execute();
$arr = $sel->fetchColumn(PDO::FETCH_ASSOC);
echo json_encode($arr['contact']); //send back json data to the client
}
?>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.