对于 AJAX 来说还是相当陌生的。我感觉我没有完全掌握它。我想向服务器提交部分数据,执行SQL查询并返回结果。这是我到目前为止所拥有的:
jQuery
j$('select[name=agent_Name]').change(function(event) {
event.preventDefault();
var agentID = j$(this).val();
post_data = {'agent_ID':agentID};
console.log("About to post data to the server");
j$.post('../include/booking_Modify.php', post_data, function(response){
if(response.type == 'AgDEpCd'){
output = response.text;
console.log(output);
}
if(response.type == 'error'){
output = response.text;
console.log(output);
}
}, 'json');
});
PHP
<?php
session_start();
require("../include/conn.php");
dbopen();
//check $_POST vars are set, exit if any missing
if(!isset($_POST["agent_ID"]))
{
$output = json_encode(array('type'=>'error', 'text' => 'Nothing was selected!'));
die($output);
}
$stmt = $conn->prepare("SELECT AgDEpCd FROM AGENTS WHERE AgentID = ?");
$stmt->bind_param('i', $_POST["agent_ID"]); // bind variables to the parameter
$stmt->execute();
$row = $result->fetch_assoc();
$AgDEpCd = $row['AgDEpCd'];
$stmt->close();
$output = json_encode(array('type'=>'AgDEpCd', 'text' => $AgDEpCd));
die($output);
?>
我检查以确保: 文件路径是正确的。 var agentID = j$(this).val();实际上获取了一个值,它确实做到了 手动将 SQL 查询输入 PHPMyAdmin 以确保我正在检索结果。 我似乎无法从服务器返回任何内容。我不确定这是否可能。请帮忙!
最佳答案
通常我只会回显并退出,简短而快速。在输入响应之前,只需 console.log
并检查它是否返回任何内容。如果它不只是检查你的 php 代码,那么除了编码输出之外还有其他错误。尝试一下。
<?php
session_start();
require("../include/conn.php");
dbopen();
//check $_POST vars are set, exit if any missing
if(!isset($_POST["agent_ID"]))
{
echo json_encode(array('type'=>'error', 'text' => 'Nothing was selected!'));
exit;
}
$stmt = $conn->prepare("SELECT AgDEpCd FROM AGENTS WHERE AgentID = ?");
$stmt->bind_param('i', $_POST["agent_ID"]); // bind variables to the parameter
$stmt->execute();
$row = $result->fetch_assoc();
$AgDEpCd = $row['AgDEpCd'];
$stmt->close();
echo json_encode(array('type'=>'AgDEpCd', 'text' => $AgDEpCd));
exit;
?>
关于php - AJAX 不返回任何数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26902358/