使用JSON提交表单并使用PHP读取


Submitting a form using JSON and reading it with 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表单工作,将数据发送到"操作"参数等。

此外,您正在尝试发送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);

注意:必须启用卷曲。

您的代码中存在以下几个问题:1.你不应该在按钮上使用onSubmit()形式,而应该使用onclick()形式。2.正如Barmar所说,您需要使用JSON.stringify()3.不确定xhr.open("POST", "/");在您的情况下是否正确(我已将其替换为test.php进行测试)

<script>
     function SendForm() {
         var username = document.login.username.value;
         var password = document.login.password.value;
         var xhr = new XMLHttpRequest();
         xhr.open("POST", "test.php");
         xhr.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
         var postData = {
             object: { child1: username, child2: password }
         }
         xhr.send(JSON.stringify(postData));
     }
 </script>
 <form name="login">
     <input class="textbox" type="text" name="username" placeholder="Username"><p>
     <input class="textbox" type="password" name="password" placeholder="Password"><p>
     <br><input class="button" type="button" onclick="SendForm();" value="Log in!">
 </form>