使用JSON提交表单并使用PHP读取
我似乎无法弄清楚这一点,我已经尝试了一切。 我想要一个表单以JSON的形式提交我的数据,然后转到PHP页面,从中输出JSON数据的结果。
我把它设置为以下,但这完全没有。
表格代码:
  <form name="login" onsubmit="SendForm();">
  <input class="textbox" type="text" name="username" placeholder="Username"><p>
  <input class="textbox" type="password" name="password" placeholder="Password"><p>
  <br><input class="submit" type="submit" value="Log in!">
  </form>
发送表格:
function SendForm() {
 var username = document.login.username.value;
 var password = document.login.password.value;
 var xhr = new XMLHttpRequest();
 xhr.open("POST", "/");
 xhr.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
 var postData = {
  object: { child1: username, child2: password }
 }
 xhr.send(postData);
 return true;
} 
PHP代码来读取它:
<?php
$json = @file_get_contents('php://input');
$array = json_decode($json, true);
if (empty($array))
    echo 'empty';
else
    print_r($array);
?>
任何帮助都很好。 谢谢!
您需要调用JSON.stringify()将JavaScript对象转换为JSON: 
xhr.send(JSON.stringify(postData));
我注意到的事情是,你应该在你的SendForm函数中返回false来取消提交并阻止表单改变页面。 否则,表单将作为常规的html表单发送,将数据发送到“action”参数等。
你也试图发送JSON,但只传递一个对象。 你应该将你的对象序列化为JSON
将对象序列化为JSON
PHP需要在输入中使用正确的json字符串,所以json_decode无法在您的情况下将字符串解码为JSON,并且您得到“空白”。 你可以使用var_dump($ json); 查看$ json的内容并检查是否有合适的json字符串
尝试这个:
$ch=curl_init(@file_get_contents('php://input'););
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$r=curl_exec($ch);
curl_close($ch);
$arr = json_decode($r,true);
if (empty($arr))
    echo 'empty';
else
    print_r($arr);
注意:您必须启用Curl。
链接地址: http://www.djcxy.com/p/46289.html