简体   繁体   English

Javascript变量到PHP变量而不重写页面

[英]Javascript Variable to PHP Variable without realoading the page

I have a problem. 我有个问题。 I have this code: 我有这个代码:

 <INPUT TYPE="button" value="Evaluare" onClick="punctaj=1;
      if (i1[1].checked) punctaj=punctaj+3;
      if (i2[0].checked) punctaj=punctaj+3;
      if (i3[3].checked) punctaj=punctaj+3;
      alert('Ai obtinut nota '+punctaj+'!');"> 

How can I send punctaj's value to a php variable, without reloading the page? 如何在不重新加载页面的情况下将punctaj的值发送到php变量?

You need to use Ajax plus json to communicate with jquery and PHP.. syntax of Jquery and Ajax 您需要使用Ajax和json与Jquery和Javascript的Jquery和Ajax语法进行通信

index.php 的index.php

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<title>Jquery Ajax</title>
<script type="text/javascript">
$(document).ready(function(e) {

$('#but').click(function()
{
    $.ajax({
        type:'POST',
        url:"values.php",
        data:"Test_Val="+$('#test').val()+"",
        success: function(result)
        {
            alert(result);
        }
    });
})

});
</script>
</head>

<body>

<input type="text" name="test" value="Hello World!" id="test" />

<input type="submit" name="submit" id="but" />
</body>
</html>

values.php values.php

<?php
if(isset($_POST['Test_Val']))
{
$value=$_POST['Test_Val'];

echo $value;
}
?>

You can use 您可以使用

document.cookie="name=value";

Then when PHP is ready to read it you can use 然后,当PHP准备好阅读它时,您可以使用

$var = $_COOKIE['name'] ;

Be aware that PHP will not be able to read javascript cookies on the same page load. 请注意,PHP将无法在同一页面加载时读取javascript cookie。 Everything PHP happens BEFORE anything javascript happens. 在任何javascript发生之前,所有PHP都会发生。

You could use AJAX to make javascript send values to a dedicated PHP page through POST or GET. 您可以使用AJAX通过POST或GET将javascript发送到专用的PHP页面。 Dont get trapped into wondering why your php cant read the javascript var even though the javascript var is above the php code. 不要陷入困境,想知道为什么你的php无法读取javascript var,即使javascript var高于php代码。 It will never work. 它永远不会奏效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM