假设我有一个带有action属性的简单表单的文件(file1.php):
echo'
<form action="foo.php" method="post">
Name: <input type="text" name="username" /><br />
Email: <input type="text" name="email" /><br />
<input type="submit" name="submit" value="Submit me!" />
</form>';
$another_var = $user_id+5;
让我们说foo.php看起来像这样:
$sql ... SELECT user_id, username... WHERE username = $_POST['username']; //or so
echo 'We got the user ID. it is in a variable!';
$user_id = $row['user_id'];
如您所见,我需要在foo.php中创建的变量$ user_id实际上在主文件file1.php中使用。 有没有办法做到这一点?我虽然返回$ user_id会起作用,但我错了: - / 一些注意事项:
有两种形式:一种用于上传文件(上面的示例),另一种用于将所有数据保存到数据库中(这就是我需要变量名称的原因)。
< / LI>这个例子只是一个例子。我并没有真正为请求的变量添加5,但我不想复制和粘贴100行代码来压倒所有人。
变量也用javascript刷新,所以我在那里看到它,但我真的不知道如何将javascript变量分配给php变量(如果可能的话)。
感谢!!!
答案 0 :(得分:1)
我可以想到两个方面。 1.
session_start();
$_SESSION['user'] = $row['user_id']
然后,只要会话被销毁,你就可以引用$ _SESSION ['user']。
另一种方法是将包含$ user_id(foo.php)的文件包含在file1.php中:
include("file1.php");
通过会话实现这一目标可能更容易。
实际上,你可以使用的更多东西是通过URL传递变量值,如果它不是需要保密的东西。
echo "<a href='file1.php?userid=" .$userid. "' > LINK </a>";
或
<?php
echo "
<html>
<head>
<meta HTTP-EQUIV='REFRESH' content='0; url=file1.php?userid=" .$userid. "'>
</head>
</html>";
然后,在file1.php上你可以像这样访问那个变量。
$userid = $_GET['userid'];
您可以随意使用$ userid。
答案 1 :(得分:1)
这是我将如何做到的。
html:
<form id="form1" action="foo.php" method="post">
<!-- form elements -->
</form>
<form id="form2" action="bar.php" method = "post">
<input type="hidden" name="filename" value="" />
<!-- other form elements -->
</form>
javascript
$('#form1').submit(function(){
var formdata = ''; //add the form data here
$.ajax({
url: "foo.php",
type: "POST",
data: formdata,
success : function(filename){
//php script returns filename
//we apply this filename as the value for the hidden field in form2
$('#form2 #filename').val(filename);
}
});
});
$('#form2').submit(function(){
//another ajax request to submit the second form
//when you are preparing the data, make sure you include the value of the field 'filename' as well
//the field 'filename' will have the actual filename returned by foo.php by this point
});
PHP
<强> foo.php 强>
//receive file in foo.php
$filename = uniqid(); //i generally use uniqid() to generate unique filenames
//do whatever with you file
//move it to a directory, store file info in a DB etc.
//return the filename to the AJAX request
echo $filename;
<强> bar.php 强>
//this script is called when the second form is submitted.
//here you can access the filename generated by the first form
$filename = $_POST['filename'];
//do your stuff here
使用Jquery Form plugin通过Ajax上传文件
$(document).ready(function(){
$('yourform').submit(function(){ //the user has clicked on submit
//do your error checking and form validation here
if (!errors)
{
$('yourform').ajaxSubmit(function(data){ //submit the form using the form plugin
alert(data); //here data will be the filename returned by the first PHP script
});
}
});
});
正如您所注意到的,您还没有指定POST数据或PHP脚本的URL。 ajaxSubmit
自动从表单中获取POST数据,并将其提交到表单action
中指定的网址