[英]Best way to check the connection to my database js
I work on a web interface which receives and send informations to a distant PostGreSQL database. 我在一个Web界面上工作,该界面接收信息并将信息发送到遥远的PostGreSQL数据库。
From what I found on the internet it seems that the best way is to create a small php script in an external .php file. 根据我在互联网上发现的信息,似乎最好的方法是在外部.php文件中创建一个小的php脚本。
I followed that idea, 我遵循了这个主意
so I have that script pg_connection.php which tests the connectivity to my database (with a pg_connect) in that style : 所以我有一个脚本pg_connection.php,它以这种样式测试与我的数据库的连接(使用pg_connect):
$db = pg_connect("host=localhost port=5432 dbname=**** user=**** password=****")
or die("Not Connected");
if ($db) {echo (Connected);} else {echo (Not Connected);}
If I launch only that pg_connection.php in my webbrowser, it works fine (I just have wrotten Connected with the correct login infos entered in my script or Not connected if I put a random ip address). 如果我仅在我的网络浏览器中启动该pg_connection.php,它就可以正常工作(我只是用在脚本中输入的正确登录信息破坏了Connected,或者如果我输入了随机IP地址则未连接)。
Then in my .js(+jquery) external script I use : 然后在我的.js(+ jquery)外部脚本中,我使用:
$(document).ready(function(){
$("#dbstatus").load("php-services/pg_connection.php");
var dbstatus = new String();
dbstatus = $("#dbstatus").val();
if (dbstatus == "Connected")
{ /*jquery code to show a green light on a section in my html page*/}
else { /*jquery code to show a red light*/}
}
And that works partially : 那部分起作用:
In my $("#dbstatus") object it will replace the default text by Connected or Not Connected, But it doesn't produce any effect on the green/red light in my conditionnal 在我的$(“#dbstatus”)对象中,它将通过“已连接”或“未连接”替换默认文本,但是在我的条件下它不会对绿色/红色指示灯产生任何影响
Then I went in my Chrome console and type dbstatus, and I realized that the content of my var is 然后我进入Chrome控制台并输入dbstatus,我意识到var的内容是
<div id="dbstatus" class="span3">Connected</div>
when I expected it to be just "Connected". 当我期望它只是“连接”时。
Any idea on how to clean that var from all these extra html stuffs ? 关于如何从所有这些额外的html内容中清理该var的想法吗?
Is there more simple method implemented in js or Jquery to check a postgreSQL database status ? 有没有在js或jQuery中实现的更简单的方法来检查postgreSQL数据库状态?
Instead of $("#dbstatus").val();
代替
$("#dbstatus").val();
use $("#dbstatus").html();
使用
$("#dbstatus").html();
. 。
Try to modify your code to: 尝试将您的代码修改为:
$db = pg_connect("host=localhost port=5432 dbname=**** user=**** password=****") or die("0");
if ($db) {echo "1";} else {echo "0"}
And in JS: 在JS中:
$(document).ready(function(){
$.ajax({
url: "http://fullpathto/php-services/pg_connection.php",
cache: false
}).done(function( result ) {
if(result=="1") {
/*jquery code to show a green light on a section in my html page*/
}
else
{
/*jquery code to show a red light*/}
}
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.