繁体   English   中英

Ajax发布到PHP不起作用

[英]Ajax post to PHP not working

嗨,我在将ajax发布到php文件时遇到了问题,但是在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+'/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;
?>

helper.php中的输出仅为1,而不是我的referens post

如果我想在具有location.reload()的同一文件中使用这种方式怎么办?

 success: function(data){
                console.log(data);
                location.reload();
            },error: function(data){
                alert('error'); 
            }
        });
    }
}(marker, i));

</script>
<?php include_once('helper.php');
 var_dump($referens); ?>

和helper.php

<?php 
   $referens = $_REQUEST['referens']; 
   echo $referens;
   echo 1;

   ?>

您的代码看起来不错。

您正在打印错误的变量。

更改

success: function(data){
  console.log(rid);
  window.location = uri+'/helper.php';
}

success: function(data){
  console.log(data); // Here you are getting return in data not as rid
  window.location = uri+'/helper.php?rid='+rid; // See, pass rid here.
}

在helper.php中

<?php 
$referens = $_REQUEST['referens']; 
echo $referens;
echo 1;
?>

根据您对其他答案和您的帖子的评论,我想提一下:

console.log(rid);
window.location = uri+'/helper.php';

在您的成功回调中rid91因为它应该按照您的注释,这是绝对正确的,因为在php文件中,您尝试访问POST变量。

但是当这一行执行window.location = uri+'/helper.php'; 然后位置发生变化并发出GET请求,因此失败。

要在PHP端获取此var,应尝试使用$_REQUEST('referens')并且必须使用以下网址发送它:

window.location = uri+'/helper.php?referens=' + rid;

并在您的PHP端:

<?php 
    $referens = $_REQUEST['referens']; // <---change here.
    echo $referens;
    echo 1;
?>

从文档[ $_REQUEST() ]:

关联数组,默认情况下包含$_GET, $_POST$_COOKIE

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM