HTML如何将用户字段输入作为json对象发送

html how to send user field input as a json object

本文关键字:json 对象 输入 用户 字段 HTML      更新时间:2023-09-26

我有一个表单,其中两个输入定义了用户名和密码,但我想将此输入作为json对象发送到服务器,这是我的html表单

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
    <form name="MY Form" action="Login" method="post">
        userid<input type="text" name="username" id="username"> <br>
        password<input type="password" name="password" id="password">
        <br> <input type="submit" name="button1" value="login"> 
    </form>
</body>
</html>

现在我如何将此数据作为json对象发送,我已经搜索过,我可以使用jquery或ajax,但我发现很难实现它,谁能告诉我如何将其作为json发送。

您可以使用.serialize()方法发送数据。

$(function() {
  $('input[name="button1"]').click(function() {
    $.post(your_url, $(this).closest('form').serialize(), function(data) {
       console.log(data);
    });
  });
});

使用object作为data的效果是一样的:

$(function() {
  $('input[name="button1"]').click(function() {
    var data = {
        username: $('#username').val(),
        password: $('#password').val(),
    };
    $.post(your_url, data, function(data) {
       console.log(data);
    });
  });
});
$( "form" ).submit(function( event ) {
  console.log( $( this ).serializeArray() );
  // do submit part here
});

作为内存服务,您只能使用javascript通过POST或GET将数据发送回服务器。您可能必须在发送之前序列化JSON。

关于如何序列化JSON对象的示例,请参阅https://stackoverflow.com/a/912247/1318677。

假设包含了JSON2和Jquery,代码可能如下所示

// create a listener on the submit event
$('form').on('submit', function (e) {
    e.preventDefault();
    // gets the data that will be submitted
    var data = $(this).serializeArray(),
    // the ajax url
        url = './request/url';
    $.ajax({
       url: url,
       type: 'POST',
       contentType:'application/json',
       data: JSON.stringify(data), //stringify
       dataType:'json',
       complete : function () {
        // do what you want here
       }
     });
    return false;
});

注意,未经测试的脚本。还要确保在调用上述脚本之前存在DOM。这可以通过在</body>结束标记之前添加脚本或使用$(document).ready(/*script here*/);

来实现。

使用这个

add id button1

html

<form action="Login" method="post" name="MY Form">
        userid<input id="username" name="username" type="text" /><br />
        password<input id="password" name="password" type="password" /><br />
        <input id="button1" name="button1" type="submit" value="login" />
    </form>
javascript

$("#button1").click(function() {
    formData = {
        username: username,
        password: password
    }
    $.ajax({
        type: 'POST',
        contentType: 'application/json',
        url: "http://localhost/login.php",
        dataType: "json",
        data: formData,
        success: function(data) {
            console.log(data);
            //success handler
        },
        error: function(data) {
            //error handler
        }
    });
});
php

<?php
/*
 * Following code will get single product details
 * A product is identified by product id (pid)
 */
// array for JSON response
$response = array();

// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// check for post data
if (isset($_POST["username"]) && isset($_POST["password"])) {
    $username = $_GET['username'];
    $password = $_GET['password'];
    // get a product from products table
    $result = mysql_query("SELECT *FROM users WHERE username = '$username' AND password  = '$password' ");
    if (!empty($result)) {
        // check for empty result
        if (mysql_num_rows($result) > 0) {
            $result = mysql_fetch_array($result);
            $user = array();
            $user["userId"] = $result["userId"];
            $user["name"] = $result["name"];
            // success
            $response["success"] = 1;
            // user node
            $response["user"] = array();
            array_push($response["user"], $user);
            // echoing JSON response
            echo json_encode($response);
        } else {
            // no product found
            $response["success"] = 0;
            $response["message"] = "No user found";
            // echo no users JSON
            echo json_encode($response);
        }
    } else {
        // no product found
        $response["success"] = 0;
        $response["message"] = "No user found";
        // echo no users JSON
        echo json_encode($response);
    }
} else {
    // required field is missing
    $response["success"] = 0;
    $response["message"] = "Required field(s) is missing";
    // echoing JSON response
    echo json_encode($response);
}
?>