使用POST纯javascript发送json对象[duplicate]

时间:2022-12-01 16:12:24

This question already has an answer here:

这个问题已经有了答案:

I want to send a JSON object to PHP server but I get an empty array there. Why is this happening?

我想向PHP服务器发送一个JSON对象,但是我得到了一个空数组。为什么会这样?

var obj = {
    username: username,
    password: password
};

var ajax = new XMLHttpRequest();
ajax.open('post', 'ajax/login_register.php');
ajax.setRequestHeader("Content-type", "application/json;charset=UTF-8");
ajax.send(JSON.stringify(obj));

1 个解决方案

#1


3  

You need to give it a name that you can reference on the server side.

您需要给它一个可以在服务器端引用的名称。

ajax.send('user=' + encodeURIComponent(JSON.stringify(obj)));

$_POST['user'] // <-- your JSON string

#1


3  

You need to give it a name that you can reference on the server side.

您需要给它一个可以在服务器端引用的名称。

ajax.send('user=' + encodeURIComponent(JSON.stringify(obj)));

$_POST['user'] // <-- your JSON string