javascript - 使用ajax在两个php函数之间发送数据
问题描述
我目前正在网站上进行用户验证。我要做的是要求用户输入凭据并按下“发送确认”按钮,然后使用某些东西(短信或信使)将代码发送给用户,并让用户将此代码插入字段并单击“确认”以检查它是否正确。我现在面临的问题是如何将正确的代码从一个 PHP 函数(我目前使用 ajax 调用)传递给另一个。出于明显的安全原因,我不能只通过 JavaScript 发送代码,但欢迎您证明我错了 :)。这是我拥有的 HTML:
<button type="button" onclick="send_sms()">Send verification</button><br>
Code from the SMS: <input type="text" id="fi" value=""><br>
<p id="res"></p>
<button type="button" onclick="check_sms()">Check</button>
<script>
function check_sms() {
jQuery.post(
ajax_object.ajax_url,
{action: "confirm_sms",
code: document.getElementById("fi").value
},
function( response ) {
// showing the result of confirmation
document.getElementById("res").textContent = response;
}
);
}
function send_sms() {
jQuery.post(
ajax_object.ajax_url,
{action: "send_sms",
phone: document.getElementById("phone").value
},
function( response ) {
// temporarely showing the code in console (shold not be there )
console.log("not an sms, but the code for now is " + response);
}
);
}
</script>
现在,在functions.php中我有:
add_action( 'wp_ajax_confirm_sms', 'confirm_sms' );
function confirm_sms() {
$code = $_POST['code'];
// yes, I know that it will not output anything after, but it is beside the point anyway.
// and yes, I will not send the real code as the output of the function (just for testing)
wp_send_json($_SESSION['real_sms_code']);
if ($code != $_SESSION['real_sms_code']) {
wp_send_json('The code is not correct, please, try again');
return;
}
wp_send_json("Nice code, awesome balls!");
}
add_action( 'wp_ajax_send_sms', 'send_sms' );
function send_sms() {
// my attempt at storing the code, not the same session as I suspected, but was worth a try
$_SESSION['real_sms_code'] = strval(rand(100000, 999999));
wp_send_json($_SESSION['real_sms_code']);
}
这里的问题是confirm_sms
函数总是输出'None'
(它应该是另一个函数设置的代码),我不知道如何解决这个问题。我正在考虑创建一个包含此代码的文件,但是
a) 不可靠
b)我无法(可靠地)识别代码属于哪个用户,因为这是在他们注册之前
c) 对于许多用户来说,这可能会很慢
必须有更好的方法来处理这个问题。
解决方案
所以我发现了这个问题:我$_SESSION
从某个地方复制了这个部分,但是那里的人从未提到你必须session_start();
在 PHP 中的函数之前使用。现在它完美无缺。有点令人沮丧,因为有人没有发布整个代码,我失去了一天,请不要那样 :)
推荐阅读
- kotlin - 为什么函数在同一范围内优先于类属性的可调用对象?
- android - 从设备浏览器启动服务
- nginx - NGINX 总是返回 {"status":400,"message":"Bad request"} - 无法使用上游 api
- r - R order geom_bar 基于一个级别
- google-bigquery - 从 Google Cloud Datastore 到 BigQuery 的增量数据传输
- arrays - 如何将特定数组项链接到表单中的字段?
- c# - Outlook 自动化
- java - java arraylist排序和优化
- javascript - 根据 x, y 位置计算角度
- typescript - 对象是“未知”类型的打字稿泛型