2017-09-11 96 views
0

在我的項目中,我使用ajax從數據庫中獲取數據。我測試數據內容,我選擇alert(valData)成功函數。但不幸的是,沒有從 ajax返回。我測試過如何使用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); 
?> 

這似乎無可厚非我的代碼,但我無法從數據庫取數據

我不知道這個錯誤,誰能幫助我?

+0

開放開發控制檯,檢查錯誤。 –

+2

請不要在會話中存儲您的密碼和用戶。這是非常不安全的。 – Erik

+1

按下F12 Chrome瀏覽器 - >網絡 - >找到您的請求,並檢查所有數據是否正確。 – RaV

回答

0

您從服務器發送回客戶端的數據不是您在ajax中指定的期望json數據的有效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被視爲對第二個爲字符串的整數查詢密切關注。請參閱When to use single quotes, double quotes, and backticks in 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 
} 
?> 
+0

在我的天,stripslashes讓ajax返回任何內容。它不是整數作爲字符串,請參閱get_ajax_csc.php代碼更新 – stack

+0

你只是不想學習 –

+0

你是什麼意思?我已經嘗試了很多次,沒有stripslashes(),Div內容不能更新到我的數據庫。 – stack

相關問題