douyi8315
2011-07-28 05:26
浏览 46
已采纳

使用PHP验证的JQuery Ajax请求

I saw this code somewhere without the PHP backend for it and have wondering how to recreate the PHP to validate my forms using this code:

$('input.signup-input[name=username]').blur(function () {
    var input = $('input.signup-input[name=username]');
    var validation = input.parent().parent().children('td.validation');
    $.post("/validate.php", {
        cmd: "verify-username",
        username: input.val()
    }, function (data) {
        if (data == 'success') {
            validation.html('<div class="success"></div>');
            input.removeClass('error-input');
        } else {
            validation.html('<div class="error">' + data.error + '</div>');
            input.addClass('error-input');
        }
    }, 'json');
});

In my PHP would I just $_POST a verify-username variable and then echo success if the field passes validation?

And if the field encounters an error would I have to json_encode an error variable in PHP so that it can be put into the data.error location of this jquery?

Anyone have any suggestions on what I should do?

图片转代码服务由CSDN问答提供 功能建议

我在没有PHP后端的地方看到了这个代码,并且想知道如何重新创建PHP来验证我的表单使用 此代码:

  $('input.signup-input [name = username]')。blur(function(){
 var input = $('input.signup  -input [name = username]'); 
 var validation = input.parent()。parent()。children('td.validation'); 
 $ .post(“/ validate.php”,{
  cmd:“verify-username”,
 username:input.val()
},function(data){
 if(data =='success'){
 validation.html('&lt; div class =  “success”&gt;&lt; / div&gt;'); 
 input.removeClass('error-input'); 
} else {
 validation.html('&lt; div class =“error”&gt;'+  data.error +'&lt; / div&gt;'); 
 input.addClass('error-input'); 
} 
},'json'); 
}); 
  <  / pre> 
 
 

在我的PHP中我只需$ _POST一个 verify-username 变量然后回显 success 如果该字段通过v alidation?

如果字段遇到错误,我必须在PHP中对json_encode error 变量进行编码,以便将其放入 data.error < / code>这个jquery的位置?

任何人对我应该做什么都有任何建议?

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dousa1630 2011-08-14 15:50
    已采纳

    Your approach is right. Just a note though... you don't have to use json since you are simply passing text and validating it. You can use the simple text/html method. Json is used when you use arrays.

    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题