[英]How do I connect javascript and MySQL via PHP?
我正在開發一個簡單的Web應用程序。 我有一個存儲值的MySQL數據庫。 當我加載網站時,我想運行一個php腳本,該腳本從數據庫中檢索所述值並將其傳遞給javascript。 然后,我使用javascript禁用按鈕或不禁用按鈕。
在我的index.html中:
<form action="someOtherScript.php" method="get">
<input type="submit" name="button1" value="Run me now!">
</form>
<script>
var value = "<?php echo $someVar; ?>";
if(value == 0){
document.getElementsByName("button1")[0].disabled = true;
}
</script>
在我的getValueFromDB.php中:
<?php
<!-- retrieve value from DB here (This part is not the problem)-->
$someVar = 0;
?>
如何在index.html中告訴我的JavaScript使用哪個php腳本(我有多個)? 因此,當網站加載時,我希望我的JavaScript從getValueFromDB.php腳本中獲取結果。
非常感謝!
您可以在頁面加載時使用Ajax嘗試
$( document ).ready(function() {
$.ajax({
url: "yourphpfile.php",
success: function(response){
if(result == 0)
{
document.getElementsByName("button1")[0].disabled = true; // instead of this maybe its better to use jquery - example below
$('#button1').prop( "disabled", true );
}
}
});
});
嘗試使用<?php include 'filepath' ; ?>
<?php include 'filepath' ; ?>
包括閱讀文檔這里 ,我認為這是你需要什么
<form action="someOtherScript.php" method="get">
<input type="submit" name="button1" value="Run me now!">
</form>
<script>
<?php include 'getValueFromDB.php' ; ?>
var value = "<?php echo $someVar; ?>";
if(value == 0){
document.getElementsByName("button1")[0].disabled = true;
}
</script>
您無法告訴javascript如何使用PHP,因為JS是一種客戶端語言和一種PHP服務器語言,並且工作流是第一個PHP,第二個JS,反之亦然。
如果您需要使用JS采集php數據,則需要使用AJAX
好(這是一個示例,未經測試)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="someOtherScript.php" method="get">
<input type="submit" name="button1" value="Run me now!">
</form>
<script>
$.ajax({
url: "getValueFromDB.php",
success: function(result){
if(result == 0){
document.getElementsByName("button1")[0].disabled = true;
}
}});
</script>
PHP
<?php
<!-- retrieve value from DB here (This part is not the problem)-->
$someVar = 0;
echo $someVar
?>
通常,您將使您的php腳本回顯您想要獲取的值,並從javascript執行ajax調用以獲取值,因此
PHP:
<?php
<!-- retrieve value from DB here (This part is not the problem)-->
$someVar = 0;
echo $someVar;
?>
和js(如果需要,可以將其直接放在html中)。
<script>
var dbData;
var ajax = new XMLHttpRequest();
ajax.open("GET", "PATH_TO_PHP_SCRIPT/getValueFromDB.php", true);
ajax.send();
ajax.onreadystatechange = function() {
if (ajax.readyState == 4 && ajax.status == 200) {
var data = ajax.responseText;
dbData=data;
//Deal with the response
}
</script>
或者,使用jQuery:
<script>
var dbData;
$.ajax({
url: "PATH_TO_YOUR_PHP_SCRIPT/getValueFromDB.php",
method: "GET"
}).done(function(d) {
dbData=d;
//Deal with the response
});
</script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.