【发布时间】:2013-05-14 06:38:15
【问题描述】:
我想要做的是通过 ajax 和 php 调用一些数据库数据。但是ajax调用不行,网上也找不到解决办法。
这是我的代码:
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);
?>
如果我在浏览器上输入该网址:http://127.0.0.1:82/blog/ws/test.php?cat=css
通过jsonEncode返回的数据是正确的,但是当我用jquery在html页面上加载它时,他无法读取数据。
test.html
<html>
<head>
<script src="//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>
提前致谢。
【问题讨论】:
-
ajax 调用正在使用'/test.php'。浏览器正在使用“/blog/ws/test.php”。除非你正在做一些你没有展示的重写。
-
你不会从你的 test.php 中得到纯 json 数据,因为你已经打印了一些 echo '
'.$dbconn->query.'
';从您的代码中删除所有回显,仅 json_encode 除外。 -
按照@ManishJangir 的建议做,然后将
var css;更改为var css = "css";,它会起作用。 -
你知道这是超级危险的,对吧?切勿将
GET之类的用户输入数据添加到 SQL 语句中。 -
解决了删除其他 echo 语句,并将 var css 设置为 var="css";感谢大家的支持。 @likeitlikeit 无论如何,如果这很危险,我应该如何以安全的方式编写相同的功能?有什么建议吗?
标签: php ajax jquery get mysqli