javascript - Mithril ajax 发送空输入

标签 javascript php jquery codeigniter mithril.js

我正在尝试使用 CodeIgniter 通过 ajax 和 Mithril.js 发送 POST 请求。但由于某种原因,输入总是为空。我尝试过使用常规的 ajax post 请求,效果很好,但 Mithril 却不行。

       m.request({
            method: "POST",
            url: "http://localhost/index.php/login",
            data: {
                username: $("#login-username").val(), 
                password: $("#login-password").val()
            }
        })
        .then(function(result) {
            console.log(result)
        })

还有 php

public function login()
    {
        $username = $this->input->post('username');

        die($username);
    }

它总是在控制台中打印“null”。有什么想法吗?

更新:

 <form class="uk-form-stacked uk-margin-remove" id="login-form" method="post" action="index.php/login">
            <fieldset class="uk-fieldset">
                <div class="uk-margin">
                    <div class="uk-inline uk-width-1-1">
                        <span class="uk-form-icon" uk-icon="icon: user"></span>
                        <input class="uk-input" id="login-username" name="username" type="text" placeholder="Username">
                    </div>
                </div>

                <div class="uk-margin">
                    <div class="uk-inline uk-width-1-1">
                        <span class="uk-form-icon" uk-icon="icon: lock"></span>
                        <input class="uk-input" id="login-password" name="password" type="password" placeholder="Password">
                    </div>
                </div>

                <div class="uk-margin" style="margin-top:10px">
                    <label ><input class="uk-checkbox" type="checkbox"> Remember me</label>
                </div>

                <input type="submit" class="uk-button uk-button-primary uk-width-1-1" value="Login">
            </fieldset>
        </form>

路线:

$route['login']['post'] = 'Users/login';

最佳答案

该代码将向服务器发送 JSON 正文,而不是表单提交。我猜您的 PHP 代码期望数据的格式类似于 <form>会发送它,因此您需要使用 FormData实例。

var data = new FormData();

data.append("username", document.querySelector("#username").value);
data.append("password", document.querySelector("#password").value);

m.request({
        method: "POST",
        url: "https://httpbin.org/post",
        data: data
    })
    .then(function(result) {
        console.log(result)
    })

我还设置了一个 JsBin,您可以在其中看到它的工作情况并查看它。

https://jsbin.com/gififo/2/

关于javascript - Mithril ajax 发送空输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48470803/

相关文章:

php - PHP 变量、方法、类等名称中的有效字符是什么?

php - 介绍Python

javascript - 使用 jQuery 访问各种元素

php - 请解释为什么 PHP switch case 总是在这段代码中执行 case 0

javascript - 如何在没有任何客户端运行的情况下更改 Firebase 上的数据?

javascript - 不同body背景onClick之间如何过渡? (尝试 2)

JavaScript insideHtml 未更改为 php session

jquery - 使用 jQuery 基于 UI 的查询生成器

javascript - 从 google map api v3 中删除路线

javascript - Google Chart API - Google 财经图表