我的 PHP 无法接收我通过 ajax 发送的“帖子”变量

my php can't receive the 'post' variabe I am sending via ajax

本文关键字:帖子 变量 ajax PHP 我的      更新时间:2023-09-26

这是我的javascript:

function fetchprov(proptype) {
    var reqdata = "condo="+proptype;
    hanapin=new XMLHttpRequest();
    hanapin.open('POST', 'testajax.php', true);
    hanapin.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
    hanapin.send(reqdata);
    hanapin.onreadystatechange = function() {
        if (hanapin.readyState == 4 && hanapin.Status == 200) {
            document.getElementById('province').innerHTML=hanapin.ResponseText
        }
    }
    window.alert(targeturl);
    window.alert(reqdata);
}

我知道函数正在接收数据,因为我使用了警报。

但在 PHP 上:

<?php 
    $findwat = $_POST['condo'];
    echo $findwat;
?>

即使我使用单独的链接打开 php 文件,它也不会回显变量

使用 jQuery 的示例:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
function fetchprov(proptype) {
    $.post("testajax.php", {condo:proptype}, function(data){
        // data is the result received from php
        alert(data);
    }); 
}

http post 请求的必填标头字段为 Content-length 。 将您的代码更改为:

function fetchprov(proptype) {
    var reqdata = "condo="+proptype;
    hanapin=new XMLHttpRequest();
    hanapin.open('POST', 'testajax.php', true);
    hanapin.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    hanapin.setRequestHeader("Content-length", reqdata.length);
    hanapin.setRequestHeader("Connection", "close");
    hanapin.send(reqdata);
    hanapin.onreadystatechange=function() {if (hanapin.readyState == 4 && hanapin.Status == 200) {document.getElementById('province').innerHTML=hanapin.ResponseText}   }
    window.alert(targeturl);
    window.alert(reqdata);
}

更好的解决方案是使用jQuery来处理Ajax