3 回答

TA貢獻(xiàn)1815條經(jīng)驗(yàn) 獲得超10個(gè)贊
在異步 Ajax 調(diào)用完成之前,您正在將長度寫入頁面。
此外,您錯(cuò)誤地使用了成功功能。
var length = 0; // Global value
$(document).ready(function() {
$.ajax({
type: 'POST',
url: 'https://www.transitum.org/linski_nach/check3.php',
dataType: "json",
data: { length: length },
success: function(data, textStatus, jqXHR) {
console.log(data); // 53
if (textStatus === 'success' && jqXHR.readyState === 4) {
length = JSON.parse(data); // Set the global variable
} else {
// Do nothing...
}
document.write(length); // Write out global length value
}
});
});

TA貢獻(xiàn)1829條經(jīng)驗(yàn) 獲得超6個(gè)贊
您可以將變量直接輸出到腳本中echo。
但是一定要檢查PHP輸出了什么樣的值。
<script src="https://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript">
// Variable for example
$length = 53;
$(document).ready(function(){
$.ajax({
type:'POST',
url:'https://www.transitum.org/linski_nach/check3.php',
dataType: "json",
data:{
length: <?php echo $length; ?> // Output variable in length property
},
success:function(data){
console.log(data);
if(data.status == 'ok'){
var length = JSON.parse(length);
} else {}
}
});
});
document.write(length);
</script>
或者,當(dāng)您有多個(gè)變量要傳遞時(shí),例如關(guān)聯(lián)數(shù)組,請(qǐng)嘗試先將其轉(zhuǎn)換為 JSON,然后進(jìn)行回顯并將其解析回 JavaScript。
<script src="https://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript">
// Array for example
$vars = array(
'length' => 53,
'string' => 'text',
'bool' => true
);
// Encode to JSON
$json = json_encode( $vars );
$(document).ready(function(){
$.ajax({
type:'POST',
url:'https://www.transitum.org/linski_nach/check3.php',
dataType: "json",
data: JSON.parse(<?php echo $json; ?>), // { length: 53, string: 'text', bool: true }
success:function(data){
console.log(data);
if(data.status == 'ok'){
var length = JSON.parse(length);
} else {}
}
});
});
document.write(length);
</script>
所以 PHP can 變量只能在內(nèi)echo聯(lián)腳本中輸出。如果您有多個(gè)變量要在 JavaScript 中使用,您可以創(chuàng)建一個(gè)內(nèi)聯(lián)腳本,將所有變量輸出到 JS 中并在其他腳本中使用它們。

TA貢獻(xiàn)1780條經(jīng)驗(yàn) 獲得超1個(gè)贊
如果 console.log 有正確的數(shù)字,試試這個(gè)
var length = data;
<script src="https://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
type:'POST',
url:'https://www.transitum.org/linski_nach/check3.php',
dataType: "json",
data:{length:length},
success:function(data){
console.log(data);
var length = data;
}
});
});
document.write(length);
</script>
- 3 回答
- 0 關(guān)注
- 266 瀏覽
添加回答
舉報(bào)