我创建了一个客户名称文本。已经注册的客户将在单击该文本字段时显示。只有该注册客户才能输入数据。我使用ajax来阻止新用户的添加。
这是ajax:
function validateForm()
{
var customerName = document.getElementById('customerName').value;
var customerId = document.getElementById('customerId').value;
var getResponse=0;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
// document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
getResponse= xmlhttp.responseText;alert(getResponse);
if(getResponse=="0")
{
return false;
}
}
};
xmlhttp.open("GET", "customer_check_ajax.php?name="+customerName+"&id="+customerId, true);
xmlhttp.send();
}
这是ajax页面customer_check_ajax.php:
<?php
require("../../config/config.inc.php");
require("../../config/Database.class.php");
require("../../config/Application.class.php");
if($_SESSION['travelType']=='Admin')
{
$check = 1;
}
else
{
$check = '';
$logId = $_SESSION['travelId'];
$proId = $_SESSION['proId'];
$check = "proId='$proId'";
}
$cusName = $_REQUEST['name'];
$cusId = $_REQUEST['id'];
$connection = mysqli_connect(DB_SERVER, DB_USER, DB_PASS, DB_DATABASE);
$qry="select * FROM ".TABLE_ACCOUNTS." WHERE ID='$cusId' and accountName='$cusName' and proId='$proId'";
$res = mysqli_query($connection, $qry);//echo $qry;
$num = mysqli_num_rows($res);
if($num>0)
echo '1';
else
echo '0';
?>
这里我会得到新用户的响应0和已注册用户的响应1。但我想在新用户添加时停止保存数据。请帮帮我。
答案 0 :(得分:0)
您正在进行异步请求,并且在函数结束后会出现ajax的答案。
要做你想做的事,你必须做同步ajax请求
xmlhttp.open("GET", "customer_check_ajax.php?name="+customerName+"&id="+customerId, false); // `false` makes the request synchronous