通过ajax调用加载mysqli php数据

我想要做的是通过ajax和php调用一些数据库数据。 但是ajax调用不起作用,我无法在网上找到解决方案。

所以这是我的代码:

test.php的

set_query("select * from posts where category = '".$cat."'"); echo '
'.$dbconn->query.'
'; $result = $dbconn->result; $num = $dbconn->num_results; $array = mysqli_fetch_assoc($result); echo json_encode($array); ?>

如果我在浏览器上输入该URL: http://127.0.0.1:82/blog/ws/test.php?cat=csshttp://127.0.0.1:82/blog/ws/test.php?cat=csshttp://127.0.0.1:82/blog/ws/test.php?cat=css

通过jsonEncode返回的数据是正确的,但是当我用jquery将它加载到html页面时,他无法读取数据。

的test.html

     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();     

提前致谢。

你的变量 css没有价值。 你想使用字符串 'css' 。 也许您希望能够加载其他类别。 所以将你的ajaxCall函数更改为

 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'); 

我只是用PDO重写了php代码,现在应该更安全了。

db.php中

 setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); } catch(PDOException $e) { echo "Connection failed, an error occured! Please contact server administrator."; //user friendly message getErrorsLog($e->getMessage()); } function closeDbConn () { $dbh = null; } function getErrorsLog($message) { $file = 'dberrors.log'; $date = date("d/m : H:i :"); // Open the file to get existing content $current = file_get_contents($file); // Append a new error message to the file $current .= $date.$message; $current .= "\r\n"; // Write the contents back to the file file_put_contents($file, $current); exit(); } ?> 

blogdata.php

 prepare("SELECT * FROM $tableName WHERE category =? ORDER BY created DESC"); } else { try { $stmt = $dbh->prepare("SELECT * FROM $tableName ORDER BY created DESC"); } catch (PDOException $e) { getErrorsLog($e->getMessage()); } } $stmt->bindValue(1, $view, PDO::PARAM_STR); $stmt->execute(); $affected_rows = $stmt->rowCount(); //Rows count if ($affected_rows == 0) { echo "The data you looking for no longer exist, please contact the administrator."; exit(); } foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) { $data[] = $row; } echo json_encode($data); closeDbConn(); ?>