仍然是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以确保我检索结果。 我似乎无法从服务器返回任何内容。我不确定这是否可能。请帮忙!
答案 0 :(得分:1)
通常我会做回声并退出,短而快。在事先输入响应时,只需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;
?>
答案 1 :(得分:1)
您没有将结果分配给$ result变量。
应该是,
$result = $stmt->execute();
答案 2 :(得分:0)
只需回显php脚本末尾的结果集。 它将被分配给ajax响应数据。
$data = array('type'=>'AgDEpCd', 'text' => $AgDEpCd);
echo json_encode($data);