[英]How can I pass a php variable to an external php file im getting data from with ajax?
[英]Getting variable values from an external PHP file
表单发布后,我试图从PHP文件获取结果:
index.php(位于http://domain2.com/中 )
<form id='loginForm' action='http://domain1.com/mail.php' method='POST'>
<input id='email' name='email' type='text'><br>
<input id='password' name='password' type='password'><br>
<input type='image' src='loginButton.png' alt ='Submit Form'/>
</form>
<script type='text/javascript'>
$(document).ready(function()
{
var error = "<?php echo json_encode($error); ?>";
document.getElementById('email').value = error;
});
</script>
mail.php(位于http://domain1.com/中 )
<?php
header('Location: http://domain2.com/'); //executes index.php
$email = $_POST['email']; //received correctly
$password = $_POST['password']; //received correctly
...
...
...
$error = 'invalid id or password';
?>
但是, $ error变量始终返回null。 这两个脚本位于同一服务器上的单独文件夹中。 我怎样才能做到这一点?
提前致谢,
苏菲亚
很抱歉使用答案部分,但是由于方法已更改,因此我想到了Ajax的方法:
index.php(位于http://domain2.com/中 )
<form id='loginForm' action='http://domain1.com/mail.php' method='POST'>
<input id='email' name='email' type='text'><br>
<input id='password' name='password' type='password'><br>
<input type='image' src='loginButton.png' alt ='Submit Form'/>
</form>
<script type='text/javascript'>
var frm = $('#loginForm');
frm.submit(function (ev)
{
$.ajax(
{
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data)
{
alert('submitted!');
}
});
ev.preventDefault();
});
</script>
mail.php(位于http://domain1.com/中 )
<?php
//header('Location: http://domain2.com/');
$email = $_POST['email'];
$password = $_POST['password'];
...
...
echo 'invalid id or password';
?>
首先,它没有执行alert('submitted!') ;其次,响应会进入哪里? 另外,它是否需要一些特殊的Ajax插件,还是标准的jQuery 1.10.1可以工作?
由于仅在出现错误的情况下才需要Ajax,如果没有错误, mail.php是否可以重定向到另一个页面?
再次感谢您提供的所有帮助和建议。
苏菲亚
问题解决了! 显然,此问题与跨域通信有关,而跨域通信又是另一回事。 在所有答复中, 有趣的是没有人注意到这一点 。
无论如何,我设法通过使用带有CURLOPT_RETURNTRANSFER选项的cURL代理来规避它。
我感谢克里斯·威拉德; 感谢您的帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.