【问题标题】:Form error handling ajax depending on user input表单错误处理 ajax 取决于用户输入
【发布时间】:2013-05-19 09:35:35
【问题描述】:

在这个问题上找不到任何有价值的答案: 它是一个非常基本的 ajax 表单进程处理程序:

$(document).ready(function(){

});
function functionToUpdate(id)
{
    var data = $('form').serialize();
    $('form').unbind('submit');                
    $.ajax({
        url: "Blahblah.php",
        type: 'POST',
        data: data,
        dataType:"json",
        beforeSend: function() {

        },
        success: function(msg) 
        {
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            alert(req.responseText);      
        }
    });
    return false;
} 

可以很好地更新 mysql 数据库中的内容。 (这是一个php文件) 我在 php 文件中检查值,并使用不同的检查,如 isset($Post) 等。

例如:

if(isset($_POST['submit']))
{
    //do stuff here if button is clicked
}
else{
    // play a nice error message
}

如何从 ajax 成功部分中显示的 url 获取此信息? 像这样:(例如)

success: function(msg) 
{
   if(post = true)
   {
       $('#succesfull').html("Succesfull query").fadeIn(800)
   }
   else
   {
       $('#fault').html("U didn't fill stuff in, failed!").fadeIn(800)
   }
},

例如这个不高兴。 但我就是无法从聚焦的 url 中获取这些数据。

所有帮助都会得到帮助。

【问题讨论】:

标签: php jquery ajax forms error-handling


【解决方案1】:

您需要将Blahblah.php 的输出重新调整为msg

success: function(msg) 
        {
           if(msg=='xxxx'){
             //Do stuff
           }
        },

编辑:

我想你可能误解了ajax调用中success:的含义。这表示调用的页面加载成功。

看看.ajax。对于这种情况,使用$.post

可能更简单

甚至$.getJSON

如果您使用 JSON,Blahblah.php 的输出必须是 json_encode

编辑:

要返回 Blahblah.php 的 html 输出,请尝试以下操作:

<?php
//must be before any output
ob_start();

//php code

$output = ob_get_contents();
$return['data'] = utf8_encode($output);
ob_end_clean();
echo json_encode($return);
?>

然后在 jQuery 中

$.post("Blahblah.php", data, function(msg)
{
  $('#succesfull').html(msg.data);
}, "json");

【讨论】:

  • 在 .php 文件中放置什么来触发这个? :P ,对不起,如果这是一个愚蠢的问题,我不经常使用 ajax。
  • 我试过了,这将返回我的整个页面:P(提交这个的页面),那么如何获取显示在php文件中的数据,也在这里显示?
  • 天哪,它不起作用,因为 data: 是用名为的变量调用的......所以当我调用 data 时,它会在提交 ajax 表单之前调用数据,所以整个页面......什么我的一个愚蠢的错误。
猜你喜欢
  • 2012-02-07
  • 2018-03-25
  • 1970-01-01
  • 1970-01-01
  • 2010-11-19
  • 1970-01-01
  • 1970-01-01
  • 2010-10-16
  • 2012-12-08
相关资源
最近更新 更多