如何使用 Ajax 调用将变量从 PHP 传递到 Javascript
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19632318/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to pass variables from PHP to Javascript using Ajax calls
提问by William
I read this postand assumed the technique in the answer would work with ajax calls. I have my ajax and php code below but it does not work.The client does not recognize the 'passed' variable. I do not know why nor how to remedy this.
我阅读了这篇文章并假设答案中的技术适用于 ajax 调用。我在下面有我的 ajax 和 php 代码,但它不起作用。客户端无法识别“passed”变量。我不知道这是为什么,也不知道如何补救。
Javascript
Javascript
var irrelevant = 'irrelevant';
$('body').click(function(){
$.ajax({
type: 'POST',
url: 'test.php',
data: {mydata: irrelevant},
success: function(){
console.log('worky');
alert(myvar); // NOT worky!
}
});
});
PHP File
PHP文件
<?php
$thing = 10;
?>
<script>
var myvar = "<?php echo $thing; ?>";
</script>
回答by zzlalani
try this in your ajax.success
在你的试试这个 ajax.success
success: function(data){
console.log('worky');
alert(data); // It should now, worky!
}
and in you php
在你的 php 中
<?php
echo 10;
?>
回答by Harish Singh
try this in php
在 php 中试试这个
<?php $thing = 10; ?>
<script>
var myvar = "<?php echo $thing; ?>";
</script>
javascript
javascript
$('body').click(function(){
$.ajax({
type: 'POST',
url: 'test.php',
data: {mydata: irrelevant},
success: function(data){
$("#hiddendiv").html(data);
alert(myvar);
}
});
});