我想根据返回html(数据)的内容创建一个if循环,那么如何在我的ajax脚本中获取由"form_treatment.php“返回的变量呢?只有当"form_treatment.php“返回一个值为"true”的var PHP时,我才想关闭包含myForm的颜色盒(一个灯箱)。
$('#myForm').submit(function() {
var myForm = $(this);
$.ajax({
type: 'POST',
url: 'form_treatment.php',
data: myForm.serialize(),
success: function (data) {
$('#message').html(data);
// Make a if loop according to what returns html(data)
}
});
return false;
});form.php:
<form method="post" action="form_treatment.php" >
<input type="text" name="user_name" value="Your name..." />
<button type="submit" >OK</button>
</form> form_treatment.php:
if ( empty($_POST['user_name']) ){
$a = false;
$b = "Name already used.";
} else {
$already_existing = verify_existence( $_POST['user_name'] );
// verification in the DB, return true or false
if( $already_existing ){
$a = false;
$b = "Name already used.";
} else {
$a = true;
$b = "Verification is OK";
}
}发布于 2011-11-30 06:20:56
尝试在$.ajax()调用中添加dataType : 'json',然后在php文件中,只使用json对象进行响应,例如:
{ "success" : true, "msg" : 'Verification is OK' }然后,在您的$.json()成功函数中,您可以访问服务器响应中的任何内容,如下所示:
if (data.success) {
alert(data.msg);
}我知道你说你想要循环,但这只是一个例子。请注意,PHP有一个名为json_encode()的小函数,它可以将数组转换为JavaScript可以很好地拾取的json对象。
发布于 2011-11-30 06:14:49
$('#myForm').submit(function() {
var myForm = $(this);
$.ajax({
type: 'POST',
url: 'form_treatment.php',
data: myForm.serialize(),
success: function (data) {
// if data is a variable like '$a="Verification is OK"':
eval(data);
if ($a == 'Verification is OK')
$("#colorBox").close() // or whatever the close method is for your plugin
else
$('#message').html($a);
}
});
return false;
});发布于 2011-11-30 06:13:26
变量"data“是从PHP文件传回的响应。因此,您可以执行以下操作:
...success: function (data) {
if (data == 'Verification is OK') {
// Make a if loop according to what returns html(data)
}
}https://stackoverflow.com/questions/8318460
复制相似问题