好的,这就是我现在面临的问题
实际上我已经在php中成功访问了JSON,但是有一个条件,没有定义特定的函数,现在,我需要从特定的PHP函数访问JSON
所以这是我的php看起来像
<?php
if(isset($_GET['func']))
{
if($_GET['func'] == "add")
addVisitor();
}
elseif(!empty($_POST['func']))
{
if($_POST['func']=="retrieve"
getData()
}
function addvisitor()
{
$servername = "localhost";
$username = "root";
$password = "@123";
$dbname = "numberofvisit";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "UPDATE visitor SET count = count +1 WHERE idvisitor = 1 ";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
}
function getData(){
$servername = "localhost";
$username = "root";
$password = "@123";
$dbname = "rating";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT avg FROM feedback WHERE idoveralRating=1";
$result = $conn->query($sql);
$pass=mysqli_fetch_assoc($result);
echo json_encode($pass["avg"]);
$conn->close();
}
?>
好的,所以我试图向服务器发送请求以运行特定的功能,通过发送func = retrieve到addVisit.php然后在运行该函数之后,我抓住服务器回应的JSON,但它似乎没有'像我期望的那样工作,这部分代码对我来说不起作用
var req = new XMLHttpRequest();
req.open("POST", "addVisit.php", true);
req.send("func=retrieve");
var jsonObject = JSON.parse(req.responseText);
那么如何使用ajax在PHP的特定功能中访问JSON?
答案 0 :(得分:1)
PHP的功能名称是case-sensitiv。 您尝试调用addVisitor()
...
if($_GET['func'] == "add")
add**V**isitor();
}
...
但是你定义的函数名是:
function add**v**isitor()
这会导致问题
这也非常有助于调试javascript是使用开发人员工具包,通常默认在您的浏览器中(例如Chrome或Opera默认情况下) 您可以通过扩展您的javascript变量,调用,返回和调试它们
console.log(variable_name_goes_here)
答案 1 :(得分:0)
试试这个: - 在按钮上单击
调用此getData函数function getData()
{
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("demo").innerHTML = xhttp.responseText;
}
};
xhttp.open("POST", "addVisit.php", true);
xhttp.send();
}