Submitting a form using JSON and reading it with PHP

I can't seem to figure this out and I've tried everything. I want a form to submit my data as a JSON, and then head to a PHP page, where it outputs the results from the JSON data.

I have it set as the following but this does absolutely nothing.

Form code:

  <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>

Send 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 code to read it:

<?php
$json = @file_get_contents('php://input');
$array = json_decode($json, true);
if (empty($array))
    echo 'empty';
else
    print_r($array);
?>

Any help at all would be great. Thanks!


您需要调用JSON.stringify()将JavaScript对象转换为JSON:

xhr.send(JSON.stringify(postData));

the thing i've noticed is that you should return false in your SendForm function to cancel submit and prevent form to change the page. Otherwise form will work as the regular html form, sending data to "action" param and etc.

Also you're trying to send JSON but passing just an object. You should serialize your object to JSON

Serializing an object to JSON

PHP wants proper json string in input so json_decode fails to decode string to JSON in your case and you're getting "empty". You can use var_dump($json); to view the contents of $json and check whether there's a proper json string


Try this:

$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);

NOTE: You must have Curl enabled.

链接地址: http://www.djcxy.com/p/46290.html

上一篇: 将保存数组的对象转换为JSON

下一篇: 使用JSON提交表单并使用PHP读取