简体   繁体   English

为什么JQuery不在PHP Action Method中发布值?

[英]Why JQuery is not posting the values in PHP Action Method?

Why JQuery is not posting the values in PHP Action Method? 为什么JQuery不在PHP Action Method中发布值?

HTML 的HTML

<form id="login" name= "login">
    <h1>Login Form</h1>
    <div>
        <input type="text" id= "userName" name = "userName" class="form-control"/>
    </div>
    <div>
        <input type="password" id= "password" name = "password" class="form-control" />
    </div>
    <div>
        <input type="button" onclick="Authenticate();" value="Log In" />          
    </div>
    <div class="clearfix"></div>
    <div class="separator">
        <div class="clearfix"></div>
        <br />
    </div>
</form>

JavaScript 的JavaScript

function Authenticate() {
    $.ajax({
        url: 'My Url',
        type: "POST",
        async: true,
        data: $('#login').serialize(),
        contentType: "application/json; charset=utf-8",
        success: function (data) {
        },
        error: function (data) {
        }
    });
}

PHP 的PHP

public function AuthenticateUser() {
    if( isset( $_POST['userName'] ) && isset( $_POST['password'] ) ) {
        header('Content-Type: application/json');
        echo json_encode( 'ok' );           
    }
    else {
        header('Content-Type: application/json');
        echo json_encode( 'Not Ok' );
    }
}

By looking at your code, what I feel is, remove this line: 通过查看您的代码,我的感受是,删除以下行:

contentType: "application/json; charset=utf-8",

It will work. 它会工作。 Everything else looks fine. 其他一切看起来都很好。

I am confident that .serialize() works, however my recommendation is to try replacing $('#login').serialize() with: 我相信.serialize()可以工作,但是我的建议是尝试将$('#login').serialize()替换为:

data: {userName: $('#userName').val(), password:$('#password').val() }

Reason is to have precise control over what data gets submitted over the AJAX call. 原因是要精确控制通过AJAX调用提交的数据。 And your AuthenticateUser should start working as expected through the POST. 并且您的AuthenticateUser应该通过POST开始按预期的方式工作。 You don't need to pass contentType: "application/json; charset=utf-8" therefore remove this line. 您不需要传递contentType: "application/json; charset=utf-8"因此删除此行。

While figuring out what parameters get passed to your app, you could 在确定将哪些参数传递给您的应用程序时,您可以

echo json_encode($_POST);

and see what gets passed to your script. 并查看传递给脚本的内容。 Naturally, you could also use error_log(json_encode($_POST)) and tail the server error log for the POST data. 当然,您也可以使用error_log(json_encode($_POST))并在服务器错误日志中添加POST数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM