$.ajax({
type:"POST",
contentType: 'application/json; charset=utf-8',
dataType: "text",
url:url,
data:myKeyVals,
dataType: 'json',
success: function(result){
var variable = result['value'];
<?php $phpvar = ?> variable <?php ;?>
}
如何将脚本变量分配给PHP变量?
答案 0 :(得分:0)
尝试这种方式
$.ajax({
type:"POST",
contentType: 'application/json; charset=utf-8',
dataType: "text",
url:url,
data:myKeyVals,
dataType: 'json',
success: function(result){
var variable = result['value'];
document.cookie = "myAjaxResult=" + variable ;
}
});
然后在您的PHP中,您可以这样做
$phpVar = $_COOKIE['myAjaxResult'];
echo $phpVar;
我不在上面尝试我的脚本,所以让我知道是否有错误
答案 1 :(得分:0)
替换此行
成功:函数(结果){
下面一行
成功:功能(结果){console.log(结果);
打开您的控制台并共享结果,您将在那里实现什么。然后,我们也许可以以正确的方式对其进行解析。
答案 2 :(得分:0)
您要执行的操作将无法工作,因为HTML(包括javascript)最后执行,并且在PHP完成后在您的页面上变为静态。这意味着您无法与PHP动态交互,也无法使用JavaScript在当前页面上再次触发PHP,因为PHP已完成呈现页面的工作。这不起作用:
<script>
$.ajax({
type:"POST",
contentType: 'application/json; charset=utf-8',
dataType: "text",
url:url,
data: myKeyVals,
dataType: 'json ',
success: function(result){
var variable = result.value;
<?php $phpvar = ?> variable <?php ;?>
}
});
</script>
<p>My variable is now <?php echo $phpvar ?></p>
起作用的是:
<script>
$.ajax({
type:"POST",
contentType: 'application/json; charset=utf-8',
dataType: "text",
url:url,
data:myKeyVals,
dataType: 'json',
success: function(result){
// Put the variable into place using javascript
$('#new-variable').text(result.value);
}
});
</script>
<p>My variable is now <span id="new-variable">old<?span></p>
在上述情况下,单词old
将替换为ajax在url
上运行的代码返回的值。如果您希望PHP保留以后的值并在当前页面上显示它,则必须更改url
中的PHP才能分配会话或cookie:
网址(来自ajax的页面):
<?php
# make sure you put session_start(); at the very top of all root/top-level pages
session_start();
# ...whatever your script is doing to get you $result['value'] goes here...
# Assign the value to session before output
$_SESSION['phpvar'] = $result['value'];
# Now output back to json for ajax
die(json_encode($result));
返回当前页面:
<?php
# At the top of the page
session_start();
# Get our value if already set
$phpvar = (!empty($_SESSION['phpvar']))? $_SESSION['phpvar'] : false;
# Continue with page script...
?>
<!-- continue with html -->
<?php if(empty($phpvar)): ?>
<script>
$.ajax({
type:"POST",
contentType: 'application/json; charset=utf-8',
dataType: "text",
url:url,
data:myKeyVals,
dataType: 'json',
success: function(result){
// Put the variable into place using javascript
$('#new-variable').text(result.value);
}
});
</script>
<?php endif ?>
<p>My variable is now <span id="new-variable"><?php echo $phpvar ?><?span></p>
答案 3 :(得分:0)
我认为您不需要将值存储在php变量中,因为您已经可以在页面上使用Javascript变量来存储值了。