使用ajax提交时,PHP post请求始终返回400

时间:2015-07-31 14:47:52

标签: php jquery ajax

我正在尝试登录,其中用户名和密码通过AJAX提交给API。问题是它总是说:

  

警告:file_get_contents(http://example.com/api/login):无法打开流:HTTP请求失败! HTTP / 1.1 400错误请求    在第20行的/classes/Login.php中

但是,如果我删除jquery并将其作为普通PHP提交,则没有问题,我得到一个"状态代码200 OK"在请求上。

我的index.php:

    <form action="ajax/processLogin.php" method="post" name="loginform" id="loginform">
        <label for="user_name">Brugernavn</label>
        <input type="text" id="user_name" name="user_name" required>

        <label for="user_password">Kodeord</label>
        <input type="password" id="user_password" name="user_password" required>

        <input type="submit" id="login" name="login" value="Log ind">
    </form>

processLogin.php:

require_once "../classes/Login.php";
$login = new Login();

$params = array('brugernavn' => $_POST['user_name'], 'password' => $_POST['user_password']);

if($login->doLogin($params)){
    echo "success";
}
else{
    echo "Fail";
}

我的Login.class.php:

    public function doLogin($params){
        $query = http_build_query($params);
        $contextData = array(
            'method' => 'POST',
            'header' => 'Connection: close\r\n' .
                        'Content-Type: application/x-www-form-urlencoded\r\n'.
                        'Content-Length: ' . strlen($query),
            'content' => $query
        );

        $context = stream_context_create(array('http' => $contextData));
        $data = file_get_contents('http://example.com/api/login', false, $context);

        $result = json_decode($data, true);

        if($result['success']){
            return true;
        }

        return false;
    }

我的main.js文件:

    $("#login").click(function(){

    var brugernavn = $("#user_name").val();
    var password = $("#user_password").val();

    if($.trim(brugernavn).length > 0 && $.trim(password).length > 0){
        $.ajax({
            url: 'ajax/processLogin.php',
            type: 'POST',
            data: 'brugernavn=' + brugernavn + '&password=' + password
        })
        .done(function(data) {
            console.log(data);
        })
        .fail(function() {
            console.log("error");
        })
        .always(function() {
            console.log("complete");
        });

    }

    return false;
});

我无法弄清问题是什么。我可能忽略了一些非常简单的事情

1 个答案:

答案 0 :(得分:3)

您忘记使用AJAX发送数据:

$.ajax({
    type: "POST",
    url: 'yoururlhere',
    data:{
        user_name: brugernavn,
        user_password: password,
    }
}).done(function(){

}).fail(function(){

}).always(function(){

});