我有这个代码来设置我的ajax请求:
function sendAjaxRequest() {
ajax.open("post", "form.php", false);
ajax.setRequestHeader("Content-Type", "application/json");
ajax.onreadystatechange = gotResponseFromServer();
ajax.send(jsonObject);
}
这一个执行请求的php:
<?php
require_once "database_connection.php";
con = mysqli_connect($host, $user, $password,$db) OR die("Failed to connect to MySQL: " . mysqli_connect_error());
$data = file_get_contents("php://input");
$decodedData = json_decode($data);
//$verifyCode = md5(rand()."");
$name = $decodedData->{'name'};
$surname = $decodedData->{'surname'};
$email = $decodedData->{'email'};
$phone = $decodedData->{'phone'};
$birthDate = $decodedData->{'birthDate'};
$studies = $decodedData->{'studies'};
$work = $decodedData->{'work'};
$married = $decodedData->{'married'};
$skills = $decodedData->{'skills'};
$hobby = $decodedData->{'hobby'};
$city = $decodedData->{'city'};
$gender = $decodedData->{'gender'};
$baptized = $decodedData->{'baptized'};
$suggestions = $decodedData->{'suggestions'};
$sql = "INSERT INTO Voluntari (_name, _surname, _email, _phone, _birthDate, ".
"_studies, _work, _married, _skills, _hobby, _city, _gender, _baptized, _suggestions) ".
"VALUES ('$name', '$surname', '$email', '$phone', '$birthDate', '$studies', '$work', '$married',".
"'$skills', '$hobby', '$city', '$gender', '$baptized', '$suggestions' );";
if(!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
} else {
//sendConfirmationMail();
echo "added";
}
mysqli_close($con);
?>
问题在于我无法异步制作ajax请求而且我不知道为什么。如果我同步执行,表单数据将添加到数据库中,但如果我以异步方式执行,ajax.status
始终为0且ajax.readyState
为1。
要将请求从异步更改为同步,我将false
放在此处:
ajax.open("post", "form.php", false);
^^^^^
我做错了什么?如何保持我的请求异步并使我的脚本工作?
答案 0 :(得分:0)
如果您在此处查看:http://www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp,您会看到参数的描述如下:
open(method,url,async)
方法:请求的类型:GET或POST
url:服务器上文件的位置
async: true(异步)或false(同步)
要使您的请求异步,您必须致电ajax.open("post", "form.php", true);
答案 1 :(得分:0)
除非对函数gotResponseFromServer
的调用返回另一个函数,否则它应该是
ajax.onreadystatechange = gotResponseFromServer;
即。你想为onreadystatechange分配一个函数,而不是它的返回值。