简体   繁体   English

Ajax,在javascript中处理php响应

[英]Ajax, handling the php response in javascript

So I'm learning Ajax and I followed this tutorial: https://phpacademy.org/course/submitting-a-form-with-ajax to create a function that works for any form. 所以我正在学习Ajax并且我遵循了本教程: https//phpacademy.org/course/submitting-a-form-with-ajax来创建适用于任何表单的函数。 This is the complete function: 这是完整的功能:

$('form.ajax').on('submit', function() {
    var that = $(this),
        url = that.attr('action'),
        type = that.attr('method'),
        data = {};

    that.find('[name]').each(function(index, value) {
        var that = $(this),
            name = that.attr('name'),
            value = that.val();

        data[name] = value;
    });

    $.ajax({
        url: url,
        type: type,
        data: data,
        success: function(response) {
            alert(url + ' ' + response);
        }
    })
    return false;
});

As you see all I'm doing is alerting the response, which in this case is php echo . 如你所见,我正在做的就是提醒响应,在这种情况下是php echo That's where my problem starts, I need a flexible and secure way to handle the javascript/php communication. 这就是我的问题开始的地方,我需要一种灵活而安全的方式来处理javascript / php通信。 Preferrably one function for all forms, maybe with if () statements instead of alert(url + ' ' + response); 最好是所有表单的一个函数,可能使用if ()语句而不是alert(url + ' ' + response); depending on the form url . 取决于表单url

The function I need is not very complicated, based on the response I get I will just update the current form with errors. 我需要的功能并不是很复杂,基于我得到的响应,我将只更新当前表单中的错误。

Aslong as I know what to use in the communication I'm fine from there, echo '1'; 只要我知道在通信中使用什么我就可以从那里开始, echo '1'; as I have now doesn't feel like the ideal solution but it's all I could handle. 因为我现在感觉不是理想的解决方案,但它是我能够处理的全部。

So, what type of response should I send from the php page, and where (in the javascript) and how is the best way to handle it? 那么,我应该从php页面发送什么类型的响应,以及在哪里(在javascript中)以及如何处理它的最佳方式? I've heard of json but having a hard time wrapping my head around it. 我听说过json但很难绕过它。 Could someone show a json response sending a basic integer thats easy for my response to pick up as an int? 有人可以显示一个json响应发送一个基本整数,这对我的响应很容易作为一个整数?

You can send back a simple JSON response via PHP and check it in your success callback. 您可以通过PHP发回一个简单的JSON响应,并在success回调中检查它。 Make sure you're setting the type to json and in your AJAX call, and using json_encode on the PHP side: 确保将type设置为json并在AJAX调用中,并在PHP端使用json_encode

$response = array('response' => 1);
echo json_encode($response);

Output should be: 输出应该是:

{ 'response' : 1 }

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

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