我有一些在mouseclick上执行的ajax代码.它调用一个名为update.php的文件来执行一系列操作,包括检查用户权限,大量数据库调用等.最后,我还希望能够从PHP返回一些变量以供回调使用,但不确定如何引用它们 - 或者是否有更好的方法来返回此信息.
$.ajax({
type: "POST",
url: "update.php",
data: dataString,
success: callback
});
function callback(data, status)
{
// $("div").text(data);
$("div.numbert").text("[first variable here]");
$("div.numbert2").text("[second variable here]");
}
Run Code Online (Sandbox Code Playgroud)
从我的update.php文件(一些片段):
if ($check_access > 0)
{
// Update database
$sql = "UPDATE db SET access = '1' WHERE user = '$user'";
$result = mysql_query($sql) or die(mysql_error());
// Give access - function returns data to variable
$value = GiveAccess($user);
// Email - function returns data to variable
$emaillist = emailAdmins($user);
} else {
$message = "Sorry you do not have access";
}
Run Code Online (Sandbox Code Playgroud)
因此,如果可能的话,我想弄清楚如何在我的回调中使用变量$ message,$ value和$ emaillist.
我想知道我是否只需要进行多个$ .ajax POST调用,每个.php函数返回一个拥有自己调用的变量?
谢谢!
尝试使用json方法的更新代码 - 感谢所有帮助 - 但似乎我最后遗漏了一件事.
$.ajax({
type: "POST",
url: "update.php",
data: dataString,
dataType: 'json',
success: callback
});
function callback(data, status)
{
// $("div").text(data);
$("div.numbert").text(data.value);
$("div.numbert2").text(data.emaillist);
Run Code Online (Sandbox Code Playgroud)
和update.php:
$storage = array();
// Update database
$sql = "UPDATE db SET access = '1' WHERE user = '$user'";
$result = mysql_query($sql) or die(mysql_error());
// Give access - function returns data to variable
$storage['value'] = "some user";
// Email - function returns data to variable
$storage['emaillist'] = "some stuff";
header('Content-type: application/json');
echo json_encode($storage);
exit(0);
Run Code Online (Sandbox Code Playgroud)
再次感谢.
您可以使用JSON包装器:
$messages = array();
$messages['value'] = GiveAccess($user);
$messages['emaillist'] = emailAdmins($user);
$messages['message'] = "Sorry you do not have access";
echo json_encode($messages);
Run Code Online (Sandbox Code Playgroud)
然后简单地使用:
data.value data.emaillist data.message
Run Code Online (Sandbox Code Playgroud)
在你的Javascript中.