我有一個關於通過AJAX/JSON傳遞給JavaScript的PHP變量的問題。AJAX GET在頁面加載時沒有更新Javascript變量
我希望var的ChronoID在頁面加載時更新它從AJAX獲取的值,從PHP代碼中獲取。儘管它在AJAX中工作正常,但它可以返回到undefined,並且不更新該變量以備後用。
我在做什麼錯誤,以及將PHP變量轉移到Javascript的最佳方式是什麼?
- scripts.js中
$(document).ready(function() {
var jsonGet;
var chronoID;
var timeworked;
var startAt;
$.ajax({
type: "GET",
url: "detectopencrono.php",
dataType: "json",
success: function (response) {
jsonGet = response;
console.log(jsonGet); // JSON Array (works)
var arr = $.map(jsonGet, function (el) {
return el;
});
console.log(arr); // JavaScript Array (after parse, works)
chronoID = arr[0]; // (works)
$("#chrono" + chronoID + "").show(200);
console.log(chronoID); // Works, shows value
}
});
console.log(chronoID); // Undefined (doesn't work)
});
- detectopencrono.php
<?php
include("connection.php");
session_start();
/*if (isset($_POST['projectname'], $_POST['startyear'], $_POST['startmonth'], $_POST['startday'], $_POST['deadyear'], $_POST['deadmonth'], $_POST['deadday'], $_POST['lider'], $_POST['hours'], $_POST['budget']))
{*/
$iduser = $_SESSION['ID'];
if(isset($_SESSION['gbsn']))
{
$wasopenresult = mysqli_query($mysqli, "SELECT ID, IsGbsn FROM subtask WHERE Crono='Y' AND IsGbsn='Y' AND IDUser='$iduser'")
or die("Não foi possivel executar o pedido.");
}
else
{
$wasopenresult = mysqli_query($mysqli, "SELECT ID, IsGbsn FROM subtask WHERE Crono='Y' AND IsGbsn='N' AND IDUser='$iduser'")
or die("Não foi possivel executar o pedido.");
}
if(mysqli_num_rows($wasopenresult)==1)
{
$rowwasopen = mysqli_fetch_assoc($wasopenresult);
$result1 = $rowwasopen['ID'];
$result2 = $rowwasopen['IsGbsn'];
echo json_encode(array('userid' => $result1,'gbsn'=> $result2));
header('Content-Type: application/json');
}
?>
[你有沒有看過瀏覽器開發工具中的AJAX請求/響應?你有沒有在項目中包含jQuery庫?是否有任何錯誤報告?你是在網絡服務器上運行的嗎?](http://jayblanchard.net/basics_of_jquery_ajax.html) –
[Little Bobby](http://bobby-tables.com/)說*** [你的腳本在SQL注入攻擊的風險。](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php)***瞭解[prepared](http:// en .wikipedia.org/wiki/Prepared_statement)[MySQLi]的聲明(http://php.net/manual/en/mysqli.quickstart.prepared-statements.php)。即使[轉義字符串](http://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string)是不安全的! –
因爲'success'是AJAX完成後調用的回調函數,所以我認爲你的第二個'console.log()'實際上是在回調完成之前運行的,而'chronoID'仍然是未定義的。如果你想用'chronoID'做一些事情,那麼在你的成功功能裏面做。 – perfect5th