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

时间:2014-03-20 05:53:48

标签: javascript jquery html ajax json

我有一个表单,其中两个输入被定义为用户名和密码,但我想将此输入作为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发送。

4 个答案:

答案 0 :(得分:3)

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

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

使用对象作为数据的效果相同:

$(function() {
  $('input[name="button1"]').click(function() {
    var data = {
        username: $('#username').val(),
        password: $('#password').val(),
    };
    $.post(your_url, data, function(data) {
       console.log(data);
    });
  });
});

答案 1 :(得分:0)

$( "form" ).submit(function( event ) {
  console.log( $( this ).serializeArray() );

  // do submit part here
});

答案 2 :(得分:0)

作为内存服务,您只能使用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*/);

来实现

答案 3 :(得分:0)

使用这个

添加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);
}
?>