簡體   English   中英

jquery 獲取 ajax 不 POST

[英]jquery to fetch ajax not POST

我想將一些 jquery 代碼轉換為 javascript 代碼

這是原樣 jquery

data.push({name: "value", value: "test"});

$.ajax({
    type: "POST",
    url: "src/routes.php",
    data:data,
    dataType: 'json',
})   

routes.php 只有這一行

print_r($_POST);

這就是回應

Array
(
    [value] => test
)

這是 javascript 代碼

data.push({name: "value", value: "test"});

const request = new Request('src/routes.php', {
     headers: new Headers({
        'Content-Type': 'application/json'
     }),
     method: 'POST',
     body: JSON.stringify(data),
});

fetch(request).then(res => res.json()).then(res => console.log(res));

但服務器以這種方式回復

Array
(
)

您不應該 json 將您的數據字符串化,僅此而已;

const request = new Request('src/routes.php', {
     headers: new Headers({
        'Content-Type': 'application/json'
     }),
     method: 'POST',
     body: data,
});

否則你必須從 php://input 讀取數據

$data = json_decode(file_get_contents('php://input'), true);
var_dump($data);

暫無
暫無

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

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