简体   繁体   中英

PHP didn't receive json data from javascript send

I try to send a request from javascript with the code below, but the problem is that php server didn't receive data in $POST or $_GET. I tried many solutions but i didn't find one.

request: function(query, type = "POST", data, async = false, callback) {

        var xhttp = new XMLHttpRequest();
        var args = [];

        if(arguments.length > 4)
            for (var i = 5; i < arguments.length; i++)
                args.push(arguments[i]);

        xhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                if(async) {
                    msg = this.responseText;
                    console.log(msg);
                    msg = JSON.parse(msg);
                    //Context.update(msg.extended);
                    var array = [msg];
                    for (var i = 0; i < args.length; i++)
                        array.push(args[i]);
                    console.log(args);
                    callback.apply(this,array);
                } else {
                    msg = this.responseText;
                    console.log(msg);
                    msg = JSON.parse(msg);
                    console.log(msg);
                }
            }
        };

        xhttp.open(type, query, async);
        xhttp.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');

        if(Object.keys(data).length > 0)
            xhttp.send(JSON.stringify(data));
        else
            xhttp.send();
        if(typeof(msg) !== "undefined")
            return msg;


    }

Maybe use an existing solution to make request, like fetch .

It will help you to no lose time on badly rewriting existing solution and focus on your real application goal.

Example code from the doc

async function postData(url = '', data = {}) {
  // Default options are marked with *
  const response = await fetch(url, {
    method: 'POST', // *GET, POST, PUT, DELETE, etc.
    mode: 'cors', // no-cors, *cors, same-origin
    cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
    credentials: 'same-origin', // include, *same-origin, omit
    headers: {
      'Content-Type': 'application/json'
      // 'Content-Type': 'application/x-www-form-urlencoded',
    },
    redirect: 'follow', // manual, *follow, error
    referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
    body: JSON.stringify(data) // body data type must match "Content-Type" header
  });
  return response.json(); // parses JSON response into native JavaScript objects
}

postData('https://example.com/answer', { answer: 42 })
  .then(data => {
    console.log(data); // JSON data parsed by `data.json()` call
  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM