鍍金池/ 問答/PHP  HTML/ 為什么$_POST超全局變量的值會出現(xiàn)一堆HTML標(biāo)簽

為什么$_POST超全局變量的值會出現(xiàn)一堆HTML標(biāo)簽

通過Ajax以post請求向服務(wù)器提交數(shù)據(jù),在PHP中輸出$_POST超全局變量的值。輸出結(jié)果如下圖
圖片描述

代碼如下:

//demo3.html

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<meta http-equiv="X-UA-Compatible" content="ie=edge">

<title>Document</title>

</head>

<body>

    <form action="Demo3.php" method="POST">
    
    用戶名:<input type='text' name='username' id='un'><br/>
    
    密碼:<input type='text' name='password' id='pw'><br/>
    
    <input type='submit' id='submit' value='提交'>
    
    </form>
    
    <p id='tips'></p>

</body>

</html>

<script>

    var submit_btn = document.getElementById('submit');
    
    var xhr = new XMLHttpRequest();
    
    submit_btn.onclick = function(e){
    
        e.preventDefault();
    
        xhr.onreadystatechange = function(){
    
        if(xhr.readyState==4 && xhr.status==200){
    
            alert(xhr.responseText);
    
        }
    
        }
    
        var username = document.getElementById('un').value; //獲得文本輸入框中的內(nèi)容
    
        var data = 'username='+username;
    
        xhr.open('post','Demo3.php');
    
        xhr.setRequestHeader('Content-Type','application/x-www-form-urlencode');
    
        xhr.send(data);
    
    }

</script>

 

//Demo3.php

<?php

    echo ($_POST);

有木有大神知道問題出在哪里。。。

回答
編輯回答
短嘆

1、你的ajax測試確實傳輸了數(shù)據(jù)到你的后臺Demo3.php,這是正確的
2、出現(xiàn)一堆HTML標(biāo)簽是因為那是PHP后臺的報錯,你應(yīng)該仔細(xì)看報錯的內(nèi)容

Notice : Array to string conversion
//因為你使用了的是echo,輸出變量應(yīng)該是文本,但是你向后臺傳輸?shù)氖且粋€數(shù)組,你不應(yīng)該用echo打印輸出,應(yīng)該使用var_dump

3、ajax確實有返回的結(jié)果,那個“正確”的結(jié)果其實就在最后一行Array,返回的是一個數(shù)組對象

2018年8月19日 14:14
編輯回答
巴扎嘿

$_POST是數(shù)組,不能使用echo來輸出,你使用print_r($_POST);輸出吧。

2018年7月31日 12:01
編輯回答
有點壞

得到空數(shù)組應(yīng)該是Header頭的問題,Content-Type應(yīng)該是application/x-www-form-urlencoded吧。少了個字母d

2018年8月2日 17:38