Parse Javascript fetch in PHP

前端 未结 3 1658
無奈伤痛
無奈伤痛 2021-01-01 19:11

I\'m calling a post request through Javascript and here\'s how it looks,

function syncDeviceId(deviceID, mod){
  var request = new Request(\'url\', {
    met         


        
3条回答
  •  鱼传尺愫
    2021-01-01 20:11

    This is because you are not setting Request's body to the correct format.

    https://developer.mozilla.org/en-US/docs/Web/API/Request/Request#Parameters

    body: Any body that you want to add to your request: this can be a Blob, BufferSource, FormData, URLSearchParams, or USVString object. Note that a request using the GET or HEAD method cannot have a body.

    The content-type header is based on the object set to body, or to the Content-Type specified in a Header object if supplied.

    So setting body to a JSON string makes the content-type header be text/plain. Even if you set the request Content-Type to application/json it wouldn't matter because PHP does not by default know how to parse incoming JSON request payloads (unless it was recently added in PHP 7).

    You can do a couple things client side

    Create a FormData object from your object, and use that as body, and a multipart/form content-type will be used

    var data = {some:"data",even:"more"};
    var fd = new FormData();
    //very simply, doesn't handle complete objects
    for(var i in data){
       fd.append(i,data[i]);
    }
    var req = new Request("url",{
       method:"POST",
       body:fd,
       mode:"cors"
    });
    

    Create a URLSearchParams object which will set the content-type to application/x-www-form-urlencoded. Note: URLSearchParams is not widely supported

    //Similar to creating a simple FormData object
    var data = {some:"data",even:"more"};
    var params = new URLSearchParams();
    for(i in data){
       params.append(i,data[i]);
    }
    var req = new Request("url",{
       method:"POST",
       body:params,
       mode:"cors"
    });
    

    Create a query string (ie a=hello&b=world) and use a Headers object to set Content-Type to application/x-form-urlencoded

    var data = {some:"data",even:"more"};
    var headers = new Headers({
        "Content-Type":"application/x-form-urlencoded"
    });
    var params = [];
    for(i in data){
       params.push(i + "=" + encodeURIComponent(data[i]));
    }
    var req = new Request("url",{
       method:"POST",
       body:params.join("&"),
       headers:headers,
       mode:"cors"
    });
    

    If you still want to send a JSON payload instead of doing the above you can, but you will have to read the raw request input and then use json_decode to get to the data

    $json = file_get_contents('php://input');
    $data = json_decode($json);
    

提交回复
热议问题