AJAX没有将值传递给PHP

时间:2014-07-26 21:31:45

标签: javascript php jquery ajax

我找不到解决这个访问通过AJAX传递给我的PHP脚本的变量的简单问题的解决方案。我甚至尝试过isset($ _ POST),但仍然无法找到用户名和密码变量。

以下是AJAX调用:

var u = $("#username", form).val();
var p = $("#password", form).val();

//testing
console.log('Username: '+u); // 'John'
console.log('Password: '+p); // 'test'

if(u !== '' && p!=='') {

    $.ajax({url: 'http://www.domain.net/php/user-login.php',
    data: {username:u,password:p},
        type: 'post',                   
    async: true,
    dataType:'json',
    beforeSend: function() {
        // This callback function will trigger before data is sent
        $.mobile.loading('show'); // This will show ajax spinner
    },
    complete: function() {
        // This callback function will trigger on data sent/received complete
        $.mobile.loading('hide'); // This will hide ajax spinner
    },
    success: function (data) {
        //save returned data to localStorage for manual button toggling later
        //window.localStorage.setItem('topGenderDataArray',data);
        console.log("Login successful: "+ data);
        console.dir(data);

        alert("Welcome back "+data['username']);
        $("#loginButton").removeAttr("disabled");
    },
    error: function (xhr,request,error) {
        // This callback function will trigger on unsuccessful action   
        alert('Network error has occurred please try again! '+xhr+ " | "+request+" | "+error);
    }
});

以下是PHP脚本的开头:

if(isset($_POST['username']) && isset($_POST['password']))
{
    $data['username'] = $_POST['username'];
    $data['password'] = $_POST['password'];
}
else{
    $data['message']= "Sorry, an error occurred! []";
    $data['user_id']= -1;
    echo json_encode($data);
    exit();
}

3 个答案:

答案 0 :(得分:6)

问题在于你的PHP代码 你在json_encode($data)子句中执行echo else,而你应该在ifelse之后执行此操作:

if(isset($_POST['username']) && isset($_POST['password']))
{
    $data['username'] = $_POST['username'];
    $data['password'] = $_POST['password'];
}
else
{
    $data['message']= "Sorry, an error occurred! []";
    $data['user_id']= -1;
}
echo json_encode($data);

答案 1 :(得分:1)

这包含你的答案:

How to get body of a POST in php?

你正在发布json数据。用户和密码不在_POST数组中。他们在请求正文中。你需要json解析它

答案 2 :(得分:1)

您只需在$data

之后打印if and else statement即可

像这样:

<?php
if(isset($_POST['username']) && isset($_POST['password']))
{
    $data['username'] = $_POST['username'];
    $data['password'] = $_POST['password'];
}
else
{
    $data['message']= "Sorry, an error occurred! []";
    $data['user_id']= -1;
}
echo json_encode($data);
exit();
?>

之后会正常工作。