我正在尝试将数据从 ajax (jquery) 响应存储到变量,因为我稍后需要在代码中使用它。
查询代码:
$(document).ready(function () {
$("#submitReg").click(function () {
var email = $("#email").val();
var password = $("#password").val();
var confpassword = $("#confpassword").val();
if (email == '' || password == '' || confpassword == '') {
swal({
type: "error",
timer: 10000,
showConfirmButton: true,
confirmButtonText: "OK",
confirmButtonColor: "#f4511e",
title: "Prosím vyplňte všetky polia!"
});
} else {
$.get("./php/register.php", {
email: email,
password: password,
confpassword: confpassword,
dataType: 'json',
//data: '1',
success: function ($data) {
var controlNumber = $data;
alert(controlNumber);
if (controlNumber != 1) {
swal({
type: "success",
timer: 10000,
showConfirmButton: true,
confirmButtonText: "OK",
confirmButtonColor: "#f4511e",
title: "Registrácia prebehla úspešne."
});
// $('#registerme')[0].reset();
} else {
swal({
type: "error",
timer: 10000,
showConfirmButton: true,
confirmButtonText: "OK",
confirmButtonColor: "#f4511e",
title: "Mail už bol zaregistrovaný."
});
}
}
})
}
});
});
PHP代码:
<?php
require_once 'connect.php';
$email = ($_GET['email']);
$password = ($_GET['password']);
$passwordR = ($_GET['confpassword']);
if ($password == $passwordR) {
$password = hash('sha256', $password);
$emailCheck = mysqli_query(connect(), "SELECT * FROM users WHERE email='" .
$email . "'");
if (mysqli_num_rows($emailCheck) > 0) {
echo json_encode(1);
die();
} else {
$sql = "INSERT INTO users (email, password) VALUES ('$email','$password')";
}
}
if (connect()->query($sql) === TRUE) {
//implementuj reset kody ptm
} else {
echo "Error: " . $sql . "<br>" . connect()->error;
}
die();
?>
我正在收到回复 - 1 所以我认为这可行,但我需要以某种方式存储它
谢谢大家的任何答案
我正在尝试将数据从 ajax (jquery) 响应存储到变量,因为我稍后需要在代码中使用它。
接受的答案var controlNumber = $data;
在 Ajax 成功回调中具有 ' ' 声明,无法从 Ajax 函数外部访问。该声明非常清楚,您无法controlNumber
在 Ajax 回调成功函数之外获取 ' ' 变量,因为it's a local variable
,declared inside a function
.. 所以最好的方法是声明一个全局 JavaScript 变量并在 Ajax 成功回调中再次重新分配值。
顺便说一句,如果我遵循“ I'm trying to store data from ajax (jquery) response to variable
”这一行,那么接受的答案就可以了。
但是,如果我遵循“ I need to use it later in code
”语句,则会在此处创建 2 个假设。
1 -如果您的代码仍在 ajax 函数中 - 那么很好
2 -如果您的代码在外部 ajax 函数上使用 ajax 响应,那么您将无法获得 '
controlNumber
' 值。如果你尝试你会得到'undefined
'
那么处理 Ajax 响应的最佳方法是什么,创建一个负责返回成功或错误响应的 ajax 对象的函数。我确定它听起来不太清楚.. ;) 这里不用担心更多或阅读更多:)
AJAX =甲同步Ĵ avaScript一个第二X ML。
AJAX 是一种创建快速动态网页的技术。
AJAX 允许通过在后台与服务器交换少量数据来异步更新网页。这意味着可以更新网页的部分内容,而无需重新加载整个页面。
内容参考:W3CSCHOOL
请注意“ asynchronously
”这个词,这意味着如果您调用 ajax 并尝试在下一行使用 ajax 响应数据,那么您不能。因为,DOM 不会等待 Ajax 响应,脚本不会停下来等待完成 ajax 过程,它会继续并且你会得到“未定义”,直到你不使用“ async: false
”选项发出 ajax 请求。*但从 jQuery 1.8 开始,不推荐使用 async: false !呜呜!!太好听了!!!@-@ *
很多人还建议在ajax成功回调中使用全局变量和设置变量值稍后使用。但问题是你尽快尝试在下一次 ajax 调用后使用变量,然后它会产生与上述相同的错误。
因此,最好的方法是使用返回 ajax 对象的函数来存储或使用或获取 Ajax 响应,以后您可以
YourAjaxObject.success(callback)
在应用程序中的任何时间使用该 ajax 对象,而无需担心。您还可以在 ajax 成功回调中使用/放置需要 ajax 响应的函数。
// global var declare here
var collect = null;
$(document).ready(function() {
var btn = $('#mySubmitButton');
btn.on('click', function(e) {
e.preventDefault();
$.post('url.php', {
id: 1
}, function(ajx_res) {
// store ajax response in global var
collect = ajx_res;
// 'I will execute last with collect = ajx_res data
alert(collect);
});
// 'I will execute first with collect = null data
alert(collect);
// When btn click again, I will execute first with previous ajx_res data
alert(collect);
});
});
$(document).ready(function() {
var btn = $('#mySubmitButton');
btn.on('click', function(e) {
e.preventDefault();
$.post('url.php', {
id: 1
}, function(ajx_res) {
// now I am local var
var collect = null;
// store ajax response in local var
collect = ajx_res;
// 'I will execute last with collect = ajx_res data
alert(collect);
});
// I will execute first with collect = undefined
alert(collect);
// When btn click again I will execute first with same collect = undefined
alert(collect);
});
});
/**
* Ajax Request & Return Response
* @param url _url action url
* @param object options send payloads
*/
function AjaxCall(_url, _options) {
return $.ajax(_url, {
method: 'POST',
data: _options,
error: function(xhr, ajaxOptions, thrownError) {
alert("Request Error:" + thrownError + " with Status" + xhr.status);
}
});
}
// I am again as global var
var collect = null;
$(document).ready(function() {
var btn = $('#mySubmitButton');
// first button, click
btn.on('click', function(e) {
e.preventDefault();
// return ajax object, and can be use within entire application via callback
collect = AjaxCall(_url, _options);
// use success callback to retrieve data
collect.success(function(ajx_res) {
// I will execute first with ajx_res
alert(ajx_res);
});
});
var btns = $('#mySubmitButtons');
// on another button, another click
btns.on('click', function(e) {
e.preventDefault();
// using previous ajax obj to get data
collect.success(function(ajx_res) {
// I will execute first with previous ajx_res
alert(ajx_res);
});
});
});
// I am again as global var
var collect = null;
$(document).ready(function() {
var btn = $('#mySubmitButton');
// first button, click
btn.on('click', function(e) {
e.preventDefault();
// return ajax object, and can be use within entire application via callback
collect = AjaxCall(_url, _options);
});
var btns = $('#mySubmitButtons');
// on another button, another click
btns.on('click', function(e) {
e.preventDefault();
// using previous ajax obj to get data
collect.success(function(ajx_res) {
// I will execute first with previous ajx_res
alert(ajx_res);
});
});
});
简而言之:
1 - 您不能在其声明区域之外使用局部变量(在函数或循环内部声明)。
2 - Ajax 不返回响应,您可以使用回调获取响应。
3 - 将 Ajax 响应存储在全局变量中以在 ajax 回调函数之外使用。
4 - 如果有任何代码,函数依赖于 ajax 响应,将它们放在 ajax 成功回调中。
5 - 如果任何特定函数需要 ajax 响应值,则在成功回调中调用这些函数并将 ajax 响应作为参数传递,或者您可以使用“注入技术”(使用相同参数运行的函数)例如
function Hello (ajx_res) {
alert (ajx_res);
// send in another function
Foo (ajx_res);
}
function Foo (ajx_res) {
alert (ajx_res);
// send in another function
Bar (ajx_res);
}
function Bar (ajx_res) {
alert (ajx_res);
}
所以我的答案是这个问题使用 Ajax Object & Get response by Callbacks。
/**
* Ajax Request & Return Response
* @param url _url action url
* @param object options send payloads
*/
function AjaxCall(_url, _options) {
return $.ajax(_url, {
method: 'POST',
data: _options,
error: function(xhr, ajaxOptions, thrownError) {
alert("Request Error:" + thrownError + " with Status" + xhr.status);
}
});
}
$(document).ready(function() {
$("#submitReg").click(function() {
var email = $("#email").val();
var password = $("#password").val();
var confpassword = $("#confpassword").val();
if (!email || !password || !confpassword) {
swal({
type: "error",
timer: 10000,
showConfirmButton: true,
confirmButtonText: "OK",
confirmButtonColor: "#f4511e",
title: "Prosím vyplňte všetky polia!"
});
} else {
var ajaxObj = AjaxCall("./php/register.php", {
email: email,
password: password,
confpassword: confpassword,
});
// your ajax callback function for success
ajaxObj.success(function(response) {
var controlNumber = response;
if (controlNumber == '1') {
swal({
type: "success",
timer: 10000,
showConfirmButton: true,
confirmButtonText: "OK",
confirmButtonColor: "#f4511e",
title: "Registrácia prebehla úspešne."
});
} else if (controlNumber == '0') {
swal({
type: "error",
timer: 10000,
showConfirmButton: true,
confirmButtonText: "OK",
confirmButtonColor: "#f4511e",
title: "Mail už bol zaregistrovaný."
});
} else {
alert(controlNumber);
}
});
}
});
});
希望这会为那些一见钟情不习惯 ajax 的初学者解惑,初恋 :D ^_^ Tadaaa.. :)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句