3 回答
TA贡献1815条经验 获得超10个赞
在异步 Ajax 调用完成之前,您正在将长度写入页面。
此外,您错误地使用了成功功能。
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贡献1829条经验 获得超6个赞
您可以将变量直接输出到脚本中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>
或者,当您有多个变量要传递时,例如关联数组,请尝试先将其转换为 JSON,然后进行回显并将其解析回 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 变量只能在内echo联脚本中输出。如果您有多个变量要在 JavaScript 中使用,您可以创建一个内联脚本,将所有变量输出到 JS 中并在其他脚本中使用它们。
TA贡献1780条经验 获得超1个赞
如果 console.log 有正确的数字,试试这个
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 关注
- 236 浏览
添加回答
举报