使用ajax将变量传递到php文件不起作用 [英] passing a variable to php file using ajax not working
问题描述
我正在尝试使用ajax单击class("women")到一个php文件时传递一个变量,但是它不起作用.这是我的代码
I am trying to pass a variable when a class("women") is clicked using ajax to a php file but it is not working. Here is my code
jquery:
$('.women').click(function(){
var test="hello";
$.ajax({
type: "POST",
url: 'data.php',
data: {'variable':test},
success:function(data){
console.log(data);
},
});
$(".women").attr('href','data.php');
})
php代码:
if (isset($_POST['variable']))
{
echo($_POST['variable']);
}
else
{
echo ("failure");
}
html:
<li class="nav-item mr-auto ml-auto" data-target="#collapsewomen">
<a class="nav-link active women productlink" href="#">Women</a>
</li>
在控制台中,我可以看到"hello",这意味着ajax在运行,但是一旦定向到php页面,我就会收到失败"的提示.我无法将测试变量传递给php文件
In the console I can see "hello" which mean ajax is working, but once directed to php page I get "failure". What I am not able to pass test variable to php file
推荐答案
ajax的目的是在不刷新页面的情况下将数据发送到URL.如果要重定向页面,则无需使用ajax
.
The purpose of ajax is to send data to a URL without refreshing the page. If you want redirect the page, there is no use of using ajax
.
进行ajax
调用不会自动保存发送的数据,并且如果您重定向到该页面,则无法使用该数据.
Doing an ajax
call will not automatically save the data sent and the data can't be use if you redirect to that page.
使用GET
$('.women').click(function(){
var test="hello";
window.location.href = "data.php?variable=" + test;
})
在您的PHP上
if (isset($_GET['variable']))
{
echo($_GET['variable']);
}
else
{
echo ("failure");
}
使用POST ,一种选择是使用隐藏形式,例如:
Using POST, one option is to use hidden form like:
在您的主页上:
$('.women').click(function(){
var test = "hello";
$('[name="variable"]').val(test); //Update the value of hidden input
$("#toPost").submit(); //Submit the form
})
HTML:
<a class="nav-link active women productlink" href="#">Women</a>
<form id="toPost" action="data.php" method="POST">
<input type="hidden" name="variable" value="">
</form>
在您的data.php上:
On your data.php:
<?php
if (isset($_POST['variable']))
{
echo($_POST['variable']);
}
else
{
echo ("failure");
}
?>
这篇关于使用ajax将变量传递到php文件不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!