Javascript Ajax-post-to-PHP不起作用
嗨,我遇到了一个问题,我正在对一个php文件进行ajax发布,但是在php文件中它是空的Javascript Ajax-post-to-PHP不起作用,javascript,php,jquery,ajax,Javascript,Php,Jquery,Ajax,嗨,我遇到了一个问题,我正在对一个php文件进行ajax发布,但是在php文件中它是空的 JS google.maps.event.addListener(marker, 'click', function(marker, i) { return function() { var rid = locations[i][4]; //get id to varible console.log(rid); $.ajax({ url: uri+'/
JS
google.maps.event.addListener(marker, 'click', function(marker, i) {
return function() {
var rid = locations[i][4]; //get id to varible
console.log(rid);
$.ajax({
url: uri+'/helper.php',
type: 'post',
data: {'referens': rid},
success: function(data){
console.log(rid);
window.location = uri+'/helper.php';
},error: function(data){
alert('error');
}
});
}
}(marker, i));
还有我的helper.php
<?php
$referens = $_POST['referens'];
echo $referens;
echo 1;
?>
<?php
$referens = $_REQUEST['referens'];
echo $referens;
echo 1;
?>
<?php
$referens = $_REQUEST['referens'];
echo $referens;
echo 1;
?>
php中的输出仅为1,而不是我的referencepost
如果我想在location.reload()的同一个文件中这样使用它呢
成功:函数(数据){
控制台日志(数据);
location.reload();
},错误:函数(数据){
警报(“错误”);
}
});
}
}(marker,i));
和helper.php
<?php
$referens = $_POST['referens'];
echo $referens;
echo 1;
?>
<?php
$referens = $_REQUEST['referens'];
echo $referens;
echo 1;
?>
<?php
$referens = $_REQUEST['referens'];
echo $referens;
echo 1;
?>
您的代码看起来不错
您打印了错误的变量
改变
success: function(data){
console.log(rid);
window.location = uri+'/helper.php';
}
到
在helper.php中
<?php
$referens = $_POST['referens'];
echo $referens;
echo 1;
?>
<?php
$referens = $_REQUEST['referens'];
echo $referens;
echo 1;
?>
<?php
$referens = $_REQUEST['referens'];
echo $referens;
echo 1;
?>
根据您对其他答案的评论和您的帖子,我想提一下:
console.log(rid);
window.location = uri+'/helper.php';
在您的成功回调中,rid
是91
,正如您的注释所示,这是绝对正确的,因为在php
文件中,您试图访问POST
变量
但是当这行执行
window.location=uri+'/helper.php'时代码>然后位置改变,它发出GET
请求,因此失败
要在PHP
末尾获取此变量,您应该尝试使用$\u请求('reference')
,并且您必须使用如下url发送它:
window.location = uri+'/helper.php?referens=' + rid;
在php端:
<?php
$referens = $_REQUEST['referens']; // <---change here.
echo $referens;
echo 1;
?>
从文档[$\u REQUEST()
]中:
一个关联数组,默认情况下包含$\u GET、$\u POST
和$\u COOKIE
以及console.log(rid)的内容
says?删除window.location并查看控制台日志输出的内容我的控制台日志显示91,正如它应该做的那样window.location=uri+'/helper.php'你为什么要这样做?我认为一个逻辑问题围绕着这个党派。但是OP怎么会看到不正确的值呢?rid应该是正确的,当我使用console.log(data)时,我得到91 1,这是正确的,但是当window.location将我带到helper.php时,它只说1如果你重定向到helper.php,那么它将不会得到E_POST参数。相反,你应该将rid传递到helper.php,然后使用$\u get.@Locos seelocation.reload()
不会向url添加数据字符串,而是可以使用window.location.href+“?reference=“+rid代码>你可以试试这个。我知道的那个,它很有效,我只是想绕过以/referencer/?references=91结尾的丑陋url,我只想用referencer/加载它,并包含helper.php中的91 var,其中我将91张贴到:PAll,然后只是张贴到当前url,或者你为什么不得到响应并更新html。我需要将我的var-rid转换为php字符串并重新加载页面,以便在同一页面上的my php if()中使用它,而不使用/referes?referes=91i解决了coockies document的问题。cookie=“ref=“+rid;location.reload()$reference=$_COOKIE['ref'];但是你明确告诉我我需要重新考虑所以谢谢JAI