javascript - 无法使 AJAX 调用或 session 正常运行

标签 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 的代码中复制的所有内容:

索引.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");
}

获取客户信息.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 '{}';
}

脚本.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);
    });
})();

最佳答案

我会尝试做一些按比例缩小的事情,看看这是否是您想要做的。只需要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);
                });
        });
    });
});

关于javascript - 无法使 AJAX 调用或 session 正常运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37094190/

相关文章:

jquery - 如何在列中显示列表项

javascript - "GAPI is not defined"消息

javascript - Discord.js 列出我所有的机器人命令

php - 使用 OOP PHP 更改枚举

PHP 只返回第一个值

jquery - 有没有一种聪明的方法来获取 jQueryUI 中的可排序目标

php - 密码确认验证失败

javascript - KendoUI AutoComplete 小部件在空时不会更新过滤器

javascript - 如何迭代子对象并将所有非对象值转换为字符串

php - GMail 421 4.7.0 稍后再试,关闭连接