简体   繁体   中英

javascript object not posting correctly to $_POST on php page using vanilla ajax

I have searched the internet and stackoverflow topics for an answer but I have not found any. I know JQuery works fine with sending the object but when I try to do the same without the framework, my post is not going through to the PHP page.

My basic 2 basic functions are:

function sendAjax(){
    let car = {type:"Fiat", model:"500", color:"white"};
    var myURL = "ajaxpost.php"; 
    var post_data = {
        myData: car
    };
    ajax(myURL, post_data); 
}

function ajax(url, post_data) {
    var params = typeof data == 'string' ? post_data : Object.keys(post_data).map(
        function(k){ return encodeURIComponent(k) + '=' + encodeURIComponent(post_data[k]) }
    ).join('&');

    var xhr = new XMLHttpRequest();
    xhr.open('POST', url, true);
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xhr.onload = function(){
        if(this.status == 200){
            document.write(this.responseText);
        } 
    }
    xhr.send(params);
}   

My PHP page at ajaxpost.php contains the following

<?php
    $data= $_POST['myData'];
    $results = print_r($data, true);
    echo $results;  // just gives me [object Object]

?>

It's because post_data.myData is an object and not a string, that it's being encoded via encodeURIComponent as [Object object] .

If you're dead-set on using www/form-data encoding, you will need a function that uses recursion to properly escape all the properties and sub-properties of the complex object.

Far be it from me to suggest using jQuery, but it has a convenience function for just this purpose, $.param(obj) .

Otherwise, you could just use JSON:

var jsonString = JSON.encode(complexObject);

Edit: I've since needed to implement this function, so I might as well share it here:

/**
 * Pack up an object of parameters into something that can be added to a GET
 * request.
 *
 * Example:
 * encodeParams({ 'foo': 'bar', 'baz': 'qux' })
 * -> "foo=bar&baz=qux"
 * @param { [key: string]: any } params - key-value store of string->anything
 * @return string URL encoded parameters
 */
var encodeParams = function (params) {
    var up = new URLSearchParams;
    var addParam = function (prefix, param) {
        if (param instanceof Array) {
            for (var _i = 0, param_1 = param; _i < param_1.length; _i++) {
                var i = param_1[_i];
                addParam(prefix + "[]", i);
            }
        }
        else if (param instanceof Object) {
            // add like associative array,
            // e.g. foo[bar][]=baz&foo[bar][]=qux
            for (var i in param) {
                if (param.hasOwnProperty(i)) {
                    addParam(prefix + "[" + i + "]", param[i]);
                }
            }
        }
        else {
            up.append(prefix, (param == null ? '' : param));
        }
    };
    for (var p in params) {
        if (params.hasOwnProperty(p)) {
            addParam(p, params[p]);
        }
    }
    return up.toString();
}; // end encodeParams()

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