Ajax:两个函数之间的客户端冲突

问题描述 投票:0回答:2

对于大学作业,我必须创建一个小型电子商务网站。登录后,用户将被重定向到主页。在此主页中,客户端将从服务器(包含要加载的某个产品)中重新获取JSON对象,以动态生成主页的DOM。

注意:我必须使用AJAX和JSON

我有这个client.js文件:

$(document).ready(function() {

    // AJAX request on submit
    $("#login_form").submit(function (e) {
        e.preventDefault();
        $.ajax({
            type: "POST",
            url: "submit.php",
            data: {
                Email: document.getElementById('login_email').value, // Email in the form
                Password: document.getElementById('login_password').value // // Password in the form
            },
            cache: false,
            success: function(){
                window.location.href = "home.php"; // load the home.php page in the default folder
            }
        });
    });
});

$(document).ready(function() {

    // AJAX request to open a channel between php and client
    function (e) {
        e.preventDefault();
        $.ajax({
            type: "GET",
            url: "queries.php",
            dataType: "json",
            success: function(data){
                var data = JSON.parse(data);
                alert(data); // debug
                showProducts(data);
            });
        });
    });
});

function showProducts(data){
    alert(data);
    // Insert object into the page DOM
}

我不知道为什么,但我登录后无法访问如果第二个Ajax请求(在php和客户端之间打开一个通道的AJAX请求)没有评论,我不知道为什么,因为代码似乎对......有什么建议吗?

javascript php jquery json ajax
2个回答
0
投票

登录操作后,您需要设置为cookie令牌作为响应

        success: function(response){
            console.log(response)
            // then set to cookie response.token
            window.location.href = "home.php";
        }

将令牌设置为cookie后,您需要将此令牌发送到下一个ajax请求url: "queries.php",


0
投票

你需要在括号中包装你的匿名函数,如果你想执行它,最后添加()

(function (e) {
    // I don't know why you need this:
    e.preventDefault();
    // etc.
})();

您还应检查该函数的内容,因为您似乎有太多的右括号,如果将dataType设置为json,则无需解析返回的值。

最后,我认为这是关于该功能所需的全部内容:

(function () {
    $.ajax({
        type: "GET",
        url: "queries.php",
        dataType: "json",
        success: function(data){
            console.log(data); // debug
            showProducts(data);
        }
    });
})();

要不就:

$.ajax({
    type: "GET",
    url: "queries.php",
    dataType: "json",
    success: function(data){
        console.log(data); // debug
        showProducts(data);
    }
});

在页面加载时直接获取它。

© www.soinside.com 2019 - 2024. All rights reserved.