簡體   English   中英

使用帶有jQuery的XMLHttpRequest將JSON數據發送到PHP

[英]Send JSON data to PHP using XMLHttpRequest w/o jQuery

我正在嘗試使用XMLHttpRequest對象從表單發送JSON數據。 我可以使用以下函數發送數據。 FireBug中沒有顯示錯誤,請求中的JSON數據顯示為FireBug。

但是,我將數據發送到echo.php ,簡單地返回內容:

<?php
print_r($_POST);
print_r($_GET);
foreach (getallheaders() as $name => $value) {
    echo "$name: $value\n";
}
echo file_get_contents('php://input');
?>

POST數組始終為空,但我可以看到file_get_contents返回的JSON字符串。 這是怎么發生的? 我究竟做錯了什么?

echo.php的輸出

Array
(
)
Array
(
)
Host: localhost
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:10.0.2) Gecko/20100101 Firefox/10.0.2
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: eo,de-de;q=0.8,de;q=0.6,en-us;q=0.4,en;q=0.2
Accept-Encoding: gzip, deflate
Connection: keep-alive
Content-Type: application/json; charset=utf-8
Referer: http://localhost/form.html
Content-Length: 88
Cookie: {{..to much data..}}
Pragma: no-cache
Cache-Control: no-cache
{"type":"my_type","comment":"commented"}

發送功能:

function submit(){
    var data={};
    data.type=document.form.type.value;
    data.comment=document.form.comment.value;

    //get right XMLHttpRequest object for current browsrer
    var x=ajaxFunction();

    var string = JSON.stringify(data);

    x.open('POST','echo.php',true);
    x.setRequestHeader('Content-type','application/json; charset=utf-8');
    x.setRequestHeader("Content-length", string.length);
    x.setRequestHeader("Connection", "close");

    x.onreadystatechange = function(){
        if (x.readyState != 4) return;
        if (x.status != 200 && x.status != 304) {
            alert('HTTP error ' + req.status);
            return;
        }

        data.resp = JSON.parse(x.responseText);
        if(data.resp.status=='success'){
            alert('That worked!');
        }else{
            alert('That didn\'t work!');
        }
    }
    x.send(string);

    return false; //prevent native form submit
}

PHP不像處理表單編碼或多部分請求那樣自動處理JSON請求。 如果你想使用JSON向PHP發送請求,你基本上是使用file_get_contents()正確地執行它。 如果你想將這些變量合並到你的全局$ _POST對象中,你可以,但我不建議這樣做,因為它可能會讓其他開發人員感到困惑。

// it's safe to overwrite the $_POST if the content-type is application/json
// because the $_POST var will be empty
$headers = getallheaders();
if ($headers["Content-Type"] == "application/json")
    $_POST = json_decode(file_get_contents("php://input"), true) ?: [];

快速注意:您不應該發送帶有Content-Type for application / json的字符集。 這應該只與text / * Content-Types一起發送。

您忘了在send函數中命名變量。 使用它的好方法是

x.send('name1='+string+'&name2=value2'); 

鑒於此,我認為你將不得不改變內容長度標題。 我不認為發送它是有用的。

您可以做的另一件事是嘗試使用GET方法。 您還可以嘗試通過以下方式更改內容類型標頭:

xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM