[英]Get value from a javascript function in a php variable
所以我的頁面上有這個javascript函數,用於計算日期。 現在,我想訪問該函數在php變量中引發的結果,以便可以使用該變量在數據庫中插入值。 該函數應在頁面加載時調用。 我一直在嘗試在過去4個小時內完成此任務,但到目前為止還沒有解決方案,歡迎提出任何建議和解決方案。
我的JS代碼:-
<script language="JavaScript">
// function to calculate local time
// in a different city
// given the city's UTC offset
function calcTime(city, offset,selDate,selHours,selMinutes) {
//alert(selDate);
//alert(selHours);
//alert(selMinutes);
//alert(offset);
var str = selDate;
var res = str.split("/");
//07,26/2014
//0,1,2
var d = new Date(res[2], res[0], res[1], selHours, selMinutes, 0, 0);
// create Date object for current location
//alert(d);
// var d = new Date();
//alert(d);
// convert to msec
// add local time zone offset
// get UTC time in msec
utc = d.getTime() + (d.getTimezoneOffset() * 60000);
// create new Date object for different city
// using supplied offset
nd = new Date(utc + (3600000*offset));
// return time as a string
return nd.toLocaleString();
}
function testTime(){
var selDate = document.getElementById("datepicker").value;
var selHours = document.getElementById("hours").value;
var selMinutes = document.getElementById("minutes").value;
var selTimeZone = document.getElementById("timezone").value;
alert(selDate);
alert(selHours);
alert(selMinutes);
alert(selTimeZone);
}
</script>
由於JS是客戶端,而PHP是服務器端,因此Javascript和PHP沒有任何交互。
PHP將在JS之前執行。
因此,您可以做的是使用隱藏字段:
<input type="hidden" name="hid" id="date">
以及javascript變量的值:
document.getElementById('date').value=date; //whatever value you want to store
然后像通常使用文本框一樣簡單地獲取該字段的值。
或者像其他人已經說過的那樣,使用AJAX從客戶端向服務器發送數據:
$.ajax({
url: something.php // current page
type: 'POST',
data: {
var1: 'date' // of if writing a JS variable remove the quotes.
},
success: function() {
// whatever
}
});
在頁面加載時調用函數: <body onload="foo()">
為了使您的JavaScript與PHP后端通信,您必須使用Ajax
。 這使您可以將信息發送到PHP文件。
為了簡單起見,我建議您使用jQuery,它有兩種有用的方法可以使用$.ajax
和$.get
您的JavaScript可能看起來像這樣:
$(document).ready(function(){
var timeToSend = calcTime(city, offset,selDate,selHours,selMinutes);
//we are sending information to saveTimeToDB.php
$.ajax('saveTimeToDB.php', {
data: {time:timeToSend}//this is an object containing all the information you want to send
}).done(function(){
//a function which gets called if the ajax call succeeded
alert('the time has been saved');
}).fail(function(){
//a function which gets called if the ajax call failed
alert('Uh-oh, something went wrong. We did not save the time');
});
});
現在,在“ saveTimeToDB.php”文件中,您可以使用以下命令訪問此變量:
$time = $_GET['time'];
然后,您應該能夠使用此變量並將其插入數據庫中。
確保對此變量進行多次檢查,以確保您沒有向數據庫注入惡意內容。
我不確定JS,但是如果功能正確,請嘗試在上面發布的代碼的</script>
之前編寫此代碼,然后打開文件(從瀏覽器):
alert calcTime('city', 3,2,12,30);
如果警報是您想要的,則:
$.get( "ajax/dowork.php?calculatedTime=" + calcTime('city', 3,2,12,30) );
...將調用dowork.php(在其中插入數據庫插入代碼,然后將有$_GET['calculatedTime']
插入)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.