简体   繁体   English

使用jQuery从PHP文件返回JSON数据

[英]Returning JSON data from PHP file using jQuery

Long time reader, first time poster. 长时间读者,第一次海报。 I'm very new to the world of jQuery and JSON and have been seeing an issue with a login script I'm running. 我是jQuery和JSON世界的新手,并且已经看到了我正在运行的登录脚本的问题。

The end goal is to capture data from a form, pass that data to a PHP file for processing via jQuery.ajax() post, compare the data against a MySQL database for authentication and return a data for either a success of failure. 最终目标是从表单中捕获数据,将该数据传递给PHP文件以通过jQuery.ajax()post进行处理,将数据与MySQL数据库进行比较以进行身份​​验证,并返回数据以确保成功失败。

My problem is that I cannot get the JSON formatted data to be passed from the PHP script back to the jQuery. 我的问题是我无法将JSON格式的数据从PHP脚本传递回jQuery。 When viewing the processing with Chrome's Developer Tools, I see that 'Login Failure'. 使用Chrome的开发者工具查看处理时,我看到“登录失败”。 I've double checked the array $rows by throwing it to my error_log file and it returns properly formatted JSON, but I just can't for the life of me get it to return to the jQuery file. 我已经通过将它扔到我的error_log文件中来仔细检查数组$ rows,并且它返回正确格式化的JSON,但我不能为我的生活让它返回到jQuery文件。 Any help is appreciated. 任何帮助表示赞赏。

My form input: 我的表格输入:

<!-- BEGIN: Login Page -->
    <section data-role="page" id="login">
        <header data-role="header" data-theme="b">
            <a href="#landing" class="ui-btn-left">Back</a>
        <h1>Please Log In</h1>
        </header>
        <div data-role="content" class="content" data-theme="b">
            <form id="loginForm" action="services.php" method="post">
                <div data-role="fieldcontain">
                    <label for="schoolID">School ID</label>
                    <input type="text" name="schoolID" id="schoolID" value=""  />

                    <label for="userName">Username</label>
                    <input type="text" name="userName" id="userName" value=""  />

                    <label for="password">Password</label>
                    <input type="password" name="password" id="password" value=""  />

                    <h3 id="notification"></h3>
                    <button data-theme="b" id="submit" type="submit">Submit</button>
            <input type="hidden" name="action" value="loginForm" id="action">
                </div>
            </form>
        </div>
        <footer data-role="footer" data-position="fixed" data-theme="b">
            <h1>Footer</h1>
        </div>
    </section>
    <!-- END: Login Page -->

My jQuery Handler: 我的jQuery Handler:

// Listen for the the submit button is clicked, serialize the data and send it off
    $('#submit').click(function(){
        var data = $("#loginForm :input").serializeArray();
    var url = $("#loginForm").attr('action');

    $.ajax({
        type: 'POST',
        url: url,
        cache: false,
        data: data,
        dataType: 'json',
            success: function(data){
            $.ajax({
                type: 'GET',
                url: "services.php",
                success: function(json){
                alert(json);
                $('#notification').append(json);
                }
            });
            }
        });
    });

And here is my PHP processing: 这是我的PHP处理:

if (isset($_POST['action'])) {
    $schoolID = $_POST['schoolID'];
    $userName = $_POST['userName'];
    $password = $_POST['password'];

    $sql = "SELECT FirstName, LastName, FamilyID, StudentID, UserID ";
    $sql .= "FROM Users ";
    $sql .= "WHERE SchoolID = '$schoolID' ";
    $sql .= "AND Username = '$userName' ";
    $sql .= "AND Password = '$password'";
    $rs = mysql_query($sql);

    $rows = array();
    while($row = mysql_fetch_array($rs, MYSQL_ASSOC)) {
        $row_array['firstName'] = $row['FirstName'];
        $row_array['lastName'] = $row['LastName'];
        $row_array['familyID'] = $row['FamilyID'];
        $row_array['studentID'] = $row['StudentID'];
        $row_array['userID'] = $row['UserID'];
        array_push($rows, $row_array);
    }

    header("Content-type: application/json", true);
    echo json_encode(array('rows'=>$rows));
    exit;

    }else{

    echo "Login Failure";
    }

Look what mistake you are making here it is very simple 看看你在这里犯了什么错,这很简单

 $.ajax({
    type: 'POST',
    url: 'services.php',
    cache: false,
    data: $('#loginForm').serialize(),
    dataType: 'json',
        success: function(data){
            alert(data);
            $('#notification').append(data);
        }
    });
});

Use serialize function of jquery. 使用jquery的serialize函数。 And when you have a parameter in success function it is not that 'data' you have in this instruction 当你有一个成功函数参数时,它不是你在这个指令中的'数据'

data : data,

It is returned from php end it is new data returned on success. 从php结束返回它是成功返回的新数据。 To avoid confliction use some thing else like new_data 为避免冲突,请使用new_data之类的其他内容

    success: function(new_data){
        alert(new_data);
        $('#notification').append(new_data);
    }

New data is in json format check it. 新数据采用json格式检查。 Use console.log to see in firebug if you are using firefox. 如果你使用的是firefox,请使用console.log查看firebug。

    success: function(new_data){
        console.log(new_data);
        alert(new_data);
        $('#notification').append(new_data);
    }

Try changing: 尝试改变:

var data = $("#loginForm :input").serializeArray();

to: 至:

var data = $("#loginForm").serialize();

This should work as I'm pretty sure "data" in the .ajax request is supposed to be a serialized string, serializeArray returns an array of objects. 这应该工作,因为我非常确定.ajax请求中的“数据”应该是序列化字符串,serializeArray返回一个对象数组。

http://api.jquery.com/serialize/ http://api.jquery.com/serialize/

http://api.jquery.com/serializeArray/ http://api.jquery.com/serializeArray/

EDIT 1: 编辑1:

This looks like an event bubbling problem. 这看起来像是一个事件冒泡问题。 Try the following: 请尝试以下方法:

Change your javascript to: 将您的javascript更改为:

function processForm(formObj) {
    var $form = $(formObj);
    var data = $form.serializeArray();
    var url = $form).attr('action');

    $.ajax({
        type: 'POST',
        url: url,
        cache: false,
        data: data,
        dataType: 'json',
        success: function(data){
            $('#notification').append(data);
        }
    });

    return false;
}

And your form to: 你的表格:

<form id="loginForm" action="services.php" method="post" onsubmit="return processForm(this)">
    <div data-role="fieldcontain">
        <label for="schoolID">School ID</label>
        <input type="text" name="schoolID" id="schoolID" value=""  />

        <label for="userName">Username</label>
        <input type="text" name="userName" id="userName" value=""  />

        <label for="password">Password</label>
        <input type="password" name="password" id="password" value=""  />

        <h3 id="notification"></h3>
        <button data-theme="b" id="submit" type="submit">Submit</button>
        <input type="hidden" name="action" value="loginForm" id="action">
    </div>
</form>

Simple answer: user error. 简单回答:用户错误。 I didn't truly understand the concept of the getJSON() function. 我没有真正理解getJSON()函数的概念。 It is meant to send the data to the PHP script and also handle the return data on success. 它旨在将数据发送到PHP脚本,并在成功时处理返回数据。 I assumed that it would require one function to send info and one function to retrieve info. 我假设它需要一个函数来发送信息和一个函数来检索信息。

Thanks for all your help! 感谢你的帮助!

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

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