我想将输入值传递给 php 会话变量。使用下面的代码,我可以将输入值发送到会话,但只出现在警告框中,或者如果我刷新页面,我不想要。我添加了一行$ ("# form1") [0] .reset ();
来刷新表单,从而将会话的值打印在屏幕上,但它不起作用。
索引.php:
<?php
@session_start();
error_reporting(0);
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>input value to php session</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<form method="post" id="form1">
<input type="text" name="field1" id="field1" onblur="run(this)">
</form>
<br /><br />
<?php echo $_SESSION['field1'];?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script language="javascript">
function run(sel) {
var text = $("#field1").val();
if (text != "") {
$.ajax({
type: "POST",
url: "input.php",
data: {
field1: text
}
}); //.done(function() {alert(text)});
}
if (done.(function() {
$("#form1").reset()
}));
}
</script>
</body>
</html>
input.php 文件:
<?php
@session_start();
error_reporting(0);
if (isset($_POST["field1"])){
$_SESSION['field1'] = $_POST["field1"];
}
?>
您可以<div>
围绕您的价值创建一个并在.done()
以下情况下更改它:
要获取会话值,您必须echo
使用它并在done()
回调中使用它:
<?php
@session_start();
error_reporting(0);
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>input value to php session</title>
</head>
<body>
<form method="post" id="form1">
<input type="text" name="field1" id="field1" onblur="run(this)">
</form>
<br /><br />
<!-- HERE wrap into a div with an ID -->
<div id="session-field"><?php echo $_SESSION['field1'];?></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script language="javascript">
function run(sel) {
var text = $("#field1").val();
if (text != "") {
$.ajax({
type: "POST",
url: "input.php",
data: { field1: text}
})
// done callback using data (wha
.done(function(data) {
$('#session-field').html(data);
$("#field1")[0].form.reset();
});
}
}
</script>
</body>
</html>
还有你的 input.php:
<?php
@session_start();
error_reporting(0);
if(isset($_POST["field1"])){
$_SESSION['field1'] = $_POST["field1"];
echo $_SESSION['field1'] ; // echo outputs
}
?>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句