简体   繁体   English

javascript对象无法使用Vanilla Ajax在PHP页面上正确发布到$ _POST

[英]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. 我已经在Internet和stackoverflow主题中搜索了答案,但没有找到任何答案。 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. 我知道JQuery可以很好地发送对象,但是当我尝试在没有框架的情况下执行同样的操作时,我的帖子将不会进入PHP页面。

My basic 2 basic functions are: 我的基本2个基本功能是:

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 我在ajaxpost.php的PHP页面包含以下内容

<?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] . 这是因为post_data.myData是一个对象而不是一个字符串,因此它是通过encodeURIComponent编码为[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. 如果您对使用www/form-data编码一无所知,则需要一个使用递归来正确转义复杂对象的所有属性和子属性的函数。

Far be it from me to suggest using jQuery, but it has a convenience function for just this purpose, $.param(obj) . 建议使用jQuery远非我本意,但是它有一个方便的功能$.param(obj)

Otherwise, you could just use JSON: 否则,您可以只使用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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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