【发布时间】:2015-08-27 11:42:47
【问题描述】:
基本上,我想用伪代码做的是:
if button_1_press {
if connection_doesnt_exist{
create_connection
echo "connected"
}
else {
echo "still connected"
}
}
if button_2_press{
if connection_exist{
close_connection
echo "disconnected"
}
else {
echo "still disconnected"
}
}
我尝试了一些方法,到目前为止我最好的方法是:
HTML
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<script type='text/javascript' src='script.js'></script>
<title>PHP AJAX Example</title>
</head>
<body>
<input type='submit' onclick='makeRequest();' value='Connect' id='b1'/>
<input type='submit' onclick='makeRequest();' value='Disconnect' id='b2'/>
<div id='ResponseDiv'>
This is a div to hold the response.
</div>
</body>
</html>
Javascript:
var xmlHttp = createXMLHttpRequest();
function createXMLHttpRequest(){
var xmlHttp;
if (window.ActiveXObject){
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e) {
xmlHttp = false;
}
}
else {
try {
xmlHttp = new XMLHttpRequest();
}
catch(e) {
xmlHttp = false;
}
}
if(!xmlHttp){
alert("Error creating the XMLHttpRequest object.");
}
else{
return xmlHttp;
}
}
function makeRequest(){
xmlHttp.onreadystatechange = function(){
if(xmlHttp.readyState == 4){
HandleResponse();
}
}
document.getElementById("b1").onclick = function () {xmlHttp.open("GET", "mysql.php?button=1", true); xmlHttp.send(null);}
document.getElementById("b2").onclick = function () {xmlHttp.open("GET", "mysql.php?button=2", true); xmlHttp.send(null);}
}
function HandleResponse(){
response = xmlHttp.responseText;
document.getElementById('ResponseDiv').innerHTML = response;
}
PHP
<?php
$servername = 'localhost';
$username = 'root';
$password = '';
$conn = new mysqli($servername, $username, $password);
if ($_GET['button']==1){
if ($conn){
echo "already connected";
}
else {
$conn = new mysqli($servername, $username, $password);
echo " connected";
}
}
if ($_GET['button']==2){
if ($conn){
echo "disconnected";
$conn->close();
}
else {
echo "still disconnected";
}
}
?>
我的问题是:
1) 当任何一个按钮第一次被点击时,它什么都不做;仅从第二次点击开始工作。
2) “已连接”按钮始终显示“已连接”。
3) 按钮“断开连接”总是显示“断开连接”
我理解这是因为每次按下按钮时,makeRequest 函数都会进行一次 AJAX 调用,每次都会创建一个 mysqli 连接,所以在评估它是否打开时,它总是为 true,但是我不知道如何解决它。
【问题讨论】:
-
只是指出,你正在使用“new mysqli”测试它是否存在......然后如果它不存在则再次使用“new mysqli”(这永远不会发生)......冗余和正如马克 B 所说,毫无意义......
标签: javascript php html mysql mysqli