简体   繁体   English

jQuery Ajax POST并返回数据

[英]jQuery Ajax POST and return data

I have a form with AJAX submit. 我有一个带有AJAX提交的表格。

This form is working, but I have the impression that the functions are not correct. 该表格有效,但是我给人的印象是功能不正确。

jQuery(document).ready(function(){
    var myForm = $("#ajax_form"), email = $("#email"), emailInfo = $("#emailInfo"), ck1 = $("#ck1"), ck2 = $("#ck2"), ck3 = $("#ck3");
    jQuery('#ajax_form').submit(function(){
        var dados = jQuery( this ).serialize();
        jQuery.ajax({
            type: "POST",
            url: "check.php", // Checking data
            data: dados,
            beforeSend: function(){
                emailInfo.html("<font color='blue'>Checking..</font>");
                if(dados == "email=") // >>> This field, how to check if the field is blank?
                {
                    email.focus();
                    emailInfo.html("<font color='red'>Required.</font>");
                    return false;
                }
            },
            success: function(data){
            if(data == "invalid")
            {
                emailInfo.html("<font color='red'>Invalid.</font>");
            }
            else if(data != "0")
            {
                email.val(data); // This field, how to display the data sent in the email field? not the return of PHP,
                ck1.css("display", "none");
                ck2.css("display", "inline");
            }
            else
            {
                ck1.css("display", "none");
                ck2.css("display", "none");
                ck3.css("display", "inline");
            }
        }
        });

        return false;
    });
});

I think that has a lot of wrong code, for example: 我认为这有很多错误的代码,例如:

if(dados == "email=") // >>> This field, how to check if the field is blank?

and >> 和>>

email.val(data); // This field, how to display the data sent in the email field? not the return of PHP,

I tried to update but not return any results 我尝试更新但未返回任何结果

Test Code 测试代码

                    //if (email.val() == "")
                //{
                    //email.focus();
                    alert(email.val()); // op1
                    alert(dados); // op2
                    alert($.trim($('email').val())); // op3
                    emailInfo.html("<font color='red'>Required.</font>");
                    return false;
                //}

if insert an email, the only option that returns is op2 email=teste@teste.com 如果插入电子邮件,则返回的唯一选项是op2 email=teste@teste.com

I think your code is trying to validate email by ajax before submitting form. 我认为您的代码正在尝试在提交表单之前通过ajax验证电子邮件。 If so this code seems ok to me out of a few points. 如果是这样的话,从几点上来说这段代码对我来说似乎还可以。

return false at the end of submit call may not work on firefox. 在提交调用结束时return false可能不适用于Firefox。 Use e.preventDefault(); 使用e.preventDefault(); . Look at this post. 这个帖子。 If you try this code on chrome it may fail beacuse you have no return true anywhere. 如果您在chrome上尝试此代码,则可能会失败,因为您在任何地方都没有return true

Your second code block is ok. 您的第二个代码块可以。 email.val(data); is equal to $("#email").val(data); 等于$("#email").val(data); . I think you are trying to set the email input value to the result. 我认为您正在尝试将电子邮件输入值设置为结果。

if(dados == "email=") can be changed to if (email.val() != '') . if(dados == "email=")可以更改为if (email.val() != '') So you wont need to dados also. 因此,您也无需使用dado。

You don't use myForm variable nowhere. 您不会无处使用myForm变量。 It should be deleted. 应该删除它。

If validating the email on server side is not a must think about validating on client side. 如果不是在服务器端验证电子邮件,则必须考虑在客户端验证。

The returned data value is echoed from your PHP file. 返回的data值将从您的PHP文件中回显。 There are two approaches to take to validate your data: 有两种验证数据的方法:

  1. Do it in the frontend with JS prior to sending your form. 在发送表单之前,请在前端使用JS进行操作。
  2. Do it with your PHP code in the separate file. 使用单独文件中的PHP代码执行此操作。

     email.val(data); // This field, how to display the data sent in the email field? not the return of PHP 

    I am guessing that you want to ensure that the value doesn't get deleted if the user sends an invalid request (thus having to type the value in again). 我猜想您要确保如果用户发送无效请求(因此必须再次输入该值),则不会删除该值。

What you can do is store the values of what the user has entered on form submit but prior to sending the AJAX request: var emailVal = email.val(); 您可以做的是在提交AJAX请求之前存储用户在表单提交中输入的值: var emailVal = email.val();

jQuery(document).ready(function(){
var myForm = $("#ajax_form"), email = $("#email"), emailInfo = $("#emailInfo"), ck1 = $("#ck1"), ck2 = $("#ck2"), ck3 = $("#ck3");
jQuery('#ajax_form').submit(function(){
    var dados = jQuery( this ).serialize();

    var emailVal = email.val(); // Assign the entered input to an emailVal variable

    jQuery.ajax({
        type: "POST",
        url: "check.php", // Checking data
        data: dados,
        beforeSend: function(){
            emailInfo.html("<font color='blue'>Checking..</font>");
            if(dados == "email=") // >>> This field, how to check if the field is blank?
            {
                email.focus();
                emailInfo.html("<font color='red'>Required.</font>");
                return false;
            }
        },
        success: function(data){
        if(data == "invalid")
        {
            emailInfo.html("<font color='red'>Invalid.</font>");
        }
        else if(data != "0")
        {

            email.val(emailVal); // Store the entered value back into the email input

            ck1.css("display", "none");
            ck2.css("display", "inline");
        }
        else
        {
            ck1.css("display", "none");
            ck2.css("display", "none");
            ck3.css("display", "inline");
        }
    }
    });

    return false;
  });
});

Another Note 另一个注意

I would also like to point out this: if(data == "invalid") 我也想指出这一点: if(data == "invalid")

I have found that PHP can send back error messages within the data along with whatever you ask it to return. 我发现PHP可以将data内的错误消息以及您要返回的内容一起发送回去。 If you have any error in your PHP code, this will never hit because invalid will never be the only string of characters in the returned data value. 如果您的PHP代码中有任何错误,将永远不会发生,因为invalid永远不会是返回data值中唯一的字符串。 To protect yourself, I would do either two things: 为了保护自己,我会做两件事:

  1. Return an HTTP error and do error handling within the error callback of the AJAX function: https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html 返回HTTP错误并在AJAX函数的error回调中执行错误处理: https : //www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
  2. Return a unique word and search for that word within the returned data string: 返回一个唯一的单词并在返回的数据字符串中搜索该单词:

PHP 的PHP

if(!validEmailCheck($email)){
   echo('invalidRAWR');
}

JS JS

if(data.indexOf('invalidRAWR') != -1)  // Built in PHP errors will never return 'invalidRAWR' 

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

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