Fetch: POST json data

后端 未结 13 1494
小蘑菇
小蘑菇 2020-11-22 03:25

I\'m trying to POST a JSON object using fetch.

From what I can understand, I need to attach a stringified object to the body of the request, e.g.:



        
相关标签:
13条回答
  • 2020-11-22 04:22

    The top answer doesn't work for PHP7, because it has wrong encoding, but I could figure the right encoding out with the other answers. This code also sends authentication cookies, which you probably want when dealing with e.g. PHP forums:

    julia = function(juliacode) {
        fetch('julia.php', {
            method: "POST",
            credentials: "include", // send cookies
            headers: {
                'Accept': 'application/json, text/plain, */*',
                //'Content-Type': 'application/json'
                "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8" // otherwise $_POST is empty
            },
            body: "juliacode=" + encodeURIComponent(juliacode)
        })
        .then(function(response) {
            return response.json(); // .text();
        })
        .then(function(myJson) {
            console.log(myJson);
        });
    }
    
    0 讨论(0)
提交回复
热议问题