[英]How can I get a PHP variable to AJAX?
I don't think I am passing the variable the right way between my separate PHP and AJAX files. 我不认为我在我的单独的PHP和AJAX文件之间以正确的方式传递变量。
I am debugging this by triggering the second condition $status = 'info';
我正在通过触发第二个条件
$status = 'info';
调试它$status = 'info';
in my PHP file. 在我的PHP文件中。
Currently, status
is coming up as "undefined" for alert(data.status);
目前,
status
即为“未定义” alert(data.status);
signup_process.php signup_process.php
if (condition){
$status = 'success';
else {
$status = 'info';
}
AJAX AJAX
function send() {
var data = $('#signup_form').serialize();
$.ajax({
type: "POST",
url: "signup_process.php",
data: data,
success: function (data) {
alert(data.status);
if (data.status == 'success') {
// everything went alright, submit
$('#signup_form').submit();
} else if (data.status == 'info')
{
console.log(data.status);
$("label#email_error").show();
return false;
}
}
});
return false;
};
I know that the 2nd condition is being triggered because I put a header redirect there just for testing and it worked fine. 我知道第二个条件是被触发的,因为我把一个标题重定向只是为了测试而且它运行正常。
Good to use json while return back data from php to ajax. 很高兴使用json同时将数据从php返回到ajax。
$return_data = array();
if (condition){
$return_data['status'] = 'success';
} else {
$return_data['status'] = 'info';
}
echo json_encode($return_data);
exit();
Now, if you are return back json data to ajax, then you need to specify return data type into ajax call as below 现在,如果你将json数据返回给ajax,那么你需要将返回数据类型指定为ajax调用,如下所示
function send() {
var data = $('#signup_form').serialize();
$.ajax({
type: "POST",
url: "signup_process.php",
data: data,
dataType: 'json',
success: function (data) {
alert(data.status);
if (data.status == 'success') {
// everything went alright, submit
$('#signup_form').submit();
} else if (data.status == 'info')
{
console.log(data.status);
$("label#email_error").show();
return false;
}
}
});
return false;
};
You should send a JSON object back from php: 你应该从php发送一个JSON对象:
$data = array();
if (condition){
$data['status'] = 'success';
else {
$data['status'] = 'info';
}
header('Content-type: application/json');
echo json_encode($data);
The json_encode() method converts the array to a JSON object so you can access each array key by name on the js side. json_encode()方法将数组转换为JSON对象,因此您可以在js端按名称访问每个数组键。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.