无法获得AJAX调用或会话功能

时间:2016-05-07 22:04:46

标签: javascript php jquery ajax session

我有一个非常类似于此线程中的服务:

Php: Form auto-fill using $_SESSION variables with multiple php files

我会问那里,但由于我没有50点声望,我不得不问一个新问题。

为了更好地理解Ajax,我想重新创建rkmax文件并查看它们是否可行。所以我将它们保存为5个单独的文件。

SESSION似乎没有存储任何发布的信息。添加了print_r($_SESSION);以跟踪当前所在的内容。此外,通过电话号码检索帐户信息的.blur事件也不起作用。

这个人已经把头撞到墙上好几天了。当通过Apache / XAMPP本地托管或在实际的Web服务器上工作时,它不会工作。所有5个文件都在同一个文件夹中,标题与rkmax的文件标题完全相同。

我理解每个功能背后的逻辑,似乎无法在任何地方找到问题。我对编码很陌生,所以它很容易就像文件结构或我自己的计算机设置一样明显?

阅读其他一些具有类似问题的StackOverflow线程,但它们似乎都不适用。

感谢您的时间。

这里是从rkmax的代码中复制的所有内容:

的index.php

<?php

session_start();

if (!isset($_SESSION['customers'])) {
    $_SESSION['customers'] = array(
        '1234567' => '{"lname": "Berg", "mi": "M", "fname": "Thomas", "account": "1234"}',
        '1122334' => '{"lname": "Jordan", "mi": "C", "fname": "Jacky", "account": "4321"}',
    );
}

require __DIR__ . '/index_template.php';

index_template.php

<!doctype html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script src="jquery.js"></script>
    <script src="scripts.js"></script>
</head>
<body>
<div style="margin-left: 300px">
    <form id="dataForm" method="post">
        <fieldset>
            <legend>User info</legend>
            <label for="fname">First name</label>
            <input id="fname" type="text" name="fname" placeholder="First name"/>

            <label for="mi">Middle inicial</label>
            <input id="mi" type="text" name="mi" placeholder="Middle Initial"/>

            <label for="lname">Last name</label>
            <input id="lname" type="text" name="lname" placeholder="Middle Initial"/>

            <label for="phone">Phone number</label>
            <input id="phone" type="text" name="phone" placeholder="000000"/>
        </fieldset>

        <fieldset>
            <legend>Account info</legend>

            <label for="account">Account</label>
            <input id="account" type="text" name="account"/>
        </fieldset>

        <input type="submit" name="submit"/>
        <input type="reset" name="clear"/>
    </form>
</div>
</body>
</html>

postCustomerInformation.php

session_start();

// example: converts $_POST['phone'] into $post_phone if exists
extract($_POST, EXTR_PREFIX_ALL, 'post');

// Validates that all required information was sent
if (isset($post_lname) && isset($post_fname) && isset($post_phone) && isset($post_account)) {
    $customer = array(
        'fname' => $post_fname,
        'lname' => $post_lname,
        'account' => $post_account,
        'mi' => isset($post_mi) ? $post_mi : '' // optional
    );

    $_SESSION['customers'][$post_phone] = json_encode($customer);
    // returns a valid json format header
    header('Content-Type: application/json');
    header("HTTP/1.0 204 No Response");
} else {
    // returns error
    header('Content-Type: application/json');
    header("HTTP/1.0 400 Bad Request");
}

getCustomerInformation.php

session_start();

// example: converts $_GET['phone'] into $get_phone if exists
extract($_GET, EXTR_PREFIX_ALL, 'get');

if (isset($get_phone) && isset($_SESSION['customers'][$get_phone])) {
    header('Content-Type: application/json');
    echo $_SESSION['customers'][$get_phone];
} else {
    header('Content-Type: application/json');
    echo '{}';
}

scripts.js中

;(function () {
    "use strict";

    function getCustomerInformation() {
        var phone = jQuery(this).val();

        if (!phone) {
            return;
        }

        jQuery.ajax({
            type: 'get',
            url: 'getCustomerInformation.php',
            data: {
                phone: phone
            },
            success: function getCustomerInformation_success(data) {
                // for each returned value is assigned to the field
                for (var i in data) {
                    if (data.hasOwnProperty(i)) {
                        $('#' + i).val(data[i]);
                    }
                }
            }
        });
    }

    function postCustomerInformation(event) {
        event.preventDefault();

        var form = jQuery(this);

        jQuery.ajax({
            type: 'post',
            url: 'postCustomerInformation.php',
            data: form.serializeArray(),
            success: function postCustomerInformation_success() {
                alert("OK");
            },
            error: function postCustomerInformation_error() {
                alert("Error");
            }
        })
    }

    // set behaviors when document is ready
    jQuery(document).ready(function document_ready() {
        jQuery('#phone').blur(getCustomerInformation);
        jQuery('#dataForm').submit(postCustomerInformation);
    });
})();

2 个答案:

答案 0 :(得分:0)

我会尝试做一些缩小的事情,看看这是不是你想要做的。您只需要3页,原始表单页面,php页面和js文件:

<强> /ajax/dispatch.php

/*
**  @param $phone [string] Gets key from session
*/
function getCustomerByPhone($phone)
    {
        if(!empty($_SESSION['customers'][$phone])) {
            // I am decoding, but if you have the ability to set,
            // create an array like below with success and data
            $values =   json_decode($_SESSION['customers'][$phone]);
            die(json_encode(array("success"=>true,"data"=>$values)));
        }
    }

function makeError()
    {
        // Send back error
        die(json_encode(array("success"=>false,"data"=>false)));
    }
/*
** @param $array [string] This will be a query string generated from the
**                        jQuery serialize, so it's to be turned to array
*/    
function updateSession($array)
    {
        // This should come back as a string, so you will need to parse it
        $data   =   false;
        parse_str(htmlspecialchars_decode($array),$data);
        // Update the session
        $_SESSION['customers'][$data['phone']]  =   json_encode($data);
        die(json_encode(array("success"=>true,"data"=>$data)));
    }

if(isset($_POST['phone'])) {
    // If already exists, return to ajax the data
    getCustomerByPhone($_POST['phone']);
}
elseif(isset($_POST['data'])) {
    updateSession($_POST['data']);
}

// If not exists, return false
makeError();

<强> /scripts.js

// I try not to duplicate things as much as possible
// so I would consider making an object to reuse
var AjaxEngine  =   function($)
    {
        this.ajax   =   function(url,data,func,method)
            {
                method  =   (typeof method === "undefined")? 'post' : 'get';
                $.ajax({
                    url: url,
                    data: data,
                    type: method,
                    success: function(response) {
                        func(response);
                    }
                });
            };
    };

$(document).ready(function(){
    // Create instance
    var Ajax        =   new AjaxEngine($);
    var dispatcher  =   '/ajax/dispatch.php';
    // On submit of form
    $(this).on('submit','#dataForm',function(e) {
        // Get the form
        var thisForm    =   $(this);
        // Stop form from firing
        e.preventDefault();
        // Run ajax to dispatch
        Ajax.ajax(dispatcher,
            // Serialize form
            $('#dataForm').serialize(),
            // Create an anonymous function to handle return
            function(response) {
                // Parse
                var resp    =   JSON.parse(response);
                // See if data exists
                if(typeof resp.data === "undefined") {
                    console.log(resp.data);
                    return false;
                }
                // If there is a hit in session
                else if(resp.success == true) {
                    // Loop through it and fill empty inputs in form
                    $.each(resp.data, function(k,v){
                        var input   =   $("input[name="+k+"]");
                        if(input.length > 0) {
                            if(input.val() == '') {
                                input.val(v);
                            }
                        }
                    });
                }
                // Run the session update
                Ajax.ajax(dispatcher,
                    // This time send an action
                    // (just to differentiate from check function)
                    {
                        "action":"update",
                        "data":thisForm.serialize()
                    },
                    function(response) {
                        // Check your console.
                        console.log(response);
                });
        });
    });
});

答案 1 :(得分:0)

从头开始,我的答案几乎是不间断的,但很快就要开始工作了,这是我迄今为止所得到的;我目前仍然成功地将SESSION数据发送回javascript并对其进行解码并成功显示。一旦我完成了这项工作,我认为将它们发送到适当的表格以及POST将是微不足道的。如果有人有任何建议来加速我通过这最后一部分,我将不胜感激。

编辑:使用最终解决方案进行编辑。

index2.php

upperLimit = position

scripts.js中

    <?php

session_start();

if (!isset($_SESSION['customers'])) {
    $_SESSION['customers'] = array(
        '1111111' => '{"phone": "1111111", "fname": "Za", "lname": "Zo", "mi": "Z", "account": "1234"}',
        '2222222' => '{"phone": "2222222", "fname": "La", "lname": "Li", "mi": "L", "account": "4321"}',
    );
}

?>

<!DOCTYPE html>

<html lang="en">
<head> 
    <title> Assignment5 </title>
    <meta charset = "utf-8" />
    <script type = "text/javascript" src = "http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script type = "text/javascript" src = "scripts.js"></script>
</head>
<body>
    <form id="myform">
        <input placeholder="Phone Number" name="phone" type="text" id="phone" maxlength="7" autofocus>
        <input placeholder="First Name" name="fname" type="text" id="fname">
        <input placeholder="Last Name" name="lname" type="text" id="lname">
        <input placeholder="Middle Initial" name="mi" type="text" id="mi">
        <input placeholder="Account Number" name="account" type="text" id="account" maxlength="4">
        <input type="submit" value="Submit">
    </form>
</body>
</html>

getPhone.php

    $(document).ready(function(){

    $("#phone").blur(function(){

        var session;
        var currentPhone = $("#phone").val();

        $.get("getPhone.php", {phone: currentPhone}, function(data) {

            for (var i in data) {
                if (data.hasOwnProperty(i)) {
                    $('#' + i).val(data[i]);
                }
            }
        });
    });

    $("form").submit(function(){

        var form = jQuery(this);

        $.post("postPhone.php", form.serializeArray(), function(data) {
            alert(data);
        });
    });
});

postPhone.php

 <?php

    session_start();

    $nowPhone = $_GET["phone"];

    if (array_key_exists($nowPhone, $_SESSION['customers'])) {
        header('Content-Type: application/json');
        echo $_SESSION['customers'][$nowPhone];
    } else {
        header('Content-Type: application/json');
        echo '{}';
    }

?>