【问题标题】:jquery ajax how to trat callbackjquery ajax如何处理回调
【发布时间】:2013-10-29 12:42:48
【问题描述】:

我正在尝试使用 jQuery 和 ajax 函数来避免重新加载页面。

所以我有一个基本的表格,我在这里将数据发送到php文件我没有问题。

我遇到的麻烦是处理返回,因为即使查询失败,它也会返回给我。

在php文件中我有那个

<?php

//Instantiation de la connexion
require_once('../../config/connexion.php');
//Initialisation des fichiers requis
include_once('../../lib_php/librairie.php');


//Initialisation des variables
function RecordObjectif(){
    //On cherche l'id de l'utilisateur
    $id_student = fetchUserId();
    if(isset($_POST['objectif'])){
        $objectif = mysql_real_escape_string($_POST['objectif']);
        $query = "INSERT INTO ...";
        mysql_query($query);
        if(mysql_affected_rows()>=0){
            $out['erreur'] = 1;
        }else{
            $out['erreur'] = 0;
        }
        echo $out;
    }else{
        return null;
    }
}

echo RecordObjectif();

在 jquery 中我的意思是 Html 页面我有这个

 $.ajax({
                    type: 'POST',
                    url: 'pages_ajax/mes-objectifs.php',
                    data: { objectif: objectif,  nom_programme: nom_programme, date_depart : date_depart, date_fin: date_fin, statut:statut},
                    dataType: "json",
                    beforeSend:function(){
                        // this is where we append a loading image
                        $('#resultat').empty()
                        $('#resultat').attr('style','text-align:center');
                        $('#resultat').append('<img src="images/loading.gif" alt="Loading..." />');
                    },
                     success:function(data){
                    // successful request; do something with the data
                    if(data.erreur==1){
                        $('#resultat').empty().removeAttr('style');
                        $('#resultat').attr('class','success').empty().append('<b>Enregistrement de votre programme terminé.</b>')
                    }
                },
                error:function(){
                    if(data.erreur==0){
                        // failed request; give feedback to user
                        $('#resultat').empty().removeAttr('style');
                        $('#resultat').attr('class','error').empty().append('<b>Erreur lors de l\'enregistrement, veuillez recommencer dans quelques minutes.</b>');
                        }
}

我不知道如何对待回报,它总是回报给我成功。

我想显示错误if $out['erreur'] = 0 我不明白的是我总是成功返回。

结果没有被解释,我还有加载图标。

我们将不胜感激任何形式的帮助。

【问题讨论】:

  • 您应该用英语而不是您的母语编写代码。 mysql_query 已弃用,您应该改用 PDO。顺便说一句,以这种方式对待data,你应该让PHP返回一个JSON数组。
  • jQuery ajax 方法中的success 函数不关心响应的值是什么,只关心有一个。因此,如果您的 php 返回 '1' 或 '0' 它仍然是一个成功的 ajax 请求。
  • 我将这个header('Content-Type: application/json; charset=utf8'); 添加到php文件中,但这还不够

标签: javascript php jquery ajax callback


【解决方案1】:

好的,您的代码中有很多内容需要查看:

  • 您正在回显RecordObjectif 函数的结果。这很好,但是在函数本身中你应该return 值而不是仅仅回显它。
  • $.ajaxsuccess 函数在 ajax 请求本身成功时调用,并不取决于您的 php 函数输出什么
  • 要访问从 php 返回的数据,您需要在 php 输出中获得 jsonencode,然后在 javascript 中再次使用 JSON.parse

仅仅为这个问题提供一些工作代码对你没有帮助,因为据我所知,你对 ajax 请求的工作原理缺乏一些基本的了解。我的建议是搜索一些简单的 ajax 请求示例,并尝试真正了解代码的哪一部分在做什么。

【讨论】:

    【解决方案2】:

    您不能在使用选择器“.”的 ajax 请求的回调中访问 PHP 变量。但是您可以像这样访问脚本回显的数据:

    .success(function(data) {
        if(data.response == 1) {
            alert('okay');
        }
    });
    

    接下来是,如果您返回 http 错误代码(不是 200 OK),则会调用错误回调。只要您的脚本在没有服务器端错误的情况下运行,您总是会返回“200 OK”。因此,您定义的错误函数将永远不会被调用。我为您提供的解决方案如下:

    $.ajax({
        type: 'POST',
        url: 'pages_ajax/mes-objectifs.php',
        data: { objectif: objectif,  nom_programme: nom_programme, date_depart : date_depart, date_fin: date_fin, statut:statut},
        dataType: "json",
        beforeSend:function(){
            // this is where we append a loading image
            $('#resultat').empty()
            $('#resultat').attr('style','text-align:center');
            $('#resultat').append('<img src="images/loading.gif" alt="Loading..." />');
       },
       always:function(data){
             $('#resultat').empty().removeAttr('style');
    
            if(data.response==1){
                   // successful request; do something with the data
                   $('#resultat').attr('class','success').empty().append('<b>Enregistrement de votre programme terminé.</b>')
            } else {
                   // failed request; give feedback to user
                   $('#resultat').attr('class','error').empty().append('<b>Erreur lors de l\'enregistrement, veuillez recommencer dans quelques minutes.</b>');
            }
       }
       });
    

    并从

    更改您的 php 脚本的行
    echo $out;
    

    echo $out['erreur'];
    

    您也可以对数组执行 json_encode() 并返回 php 数组的 json 数据,但在我看来这是一个开销。

    【讨论】:

      【解决方案3】:

      error:function(){中删除下面的代码块

      if(data.erreur==0){
          // failed request; give feedback to user
          $('#resultat').empty().removeAttr('style');
          $('#resultat').attr('class','error').empty().append('<b>Erreur lors de l\'enregistrement, veuillez recommencer dans quelques minutes.</b>');
      }
      

      并将其放入success:function(data){,如下所示:

      success:function(data){
          // successful request; do something with the data
          if(data.erreur==1){
              $('#resultat').empty().removeAttr('style');
              $('#resultat').attr('class','success').empty().append('<b>Enregistrement de votre programme terminé.</b>')
          }
          // if faliure
          else if(data.erreur==0){
              // failed request; give feedback to user
              $('#resultat').empty().removeAttr('style');
              $('#resultat').attr('class','error').empty().append('<b>Erreur lors de l\'enregistrement, veuillez recommencer dans quelques minutes.</b>');
          }
      }
      

      这应该做的工作!

      【讨论】:

        猜你喜欢
        • 2011-03-23
        • 2012-11-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-06-05
        • 1970-01-01
        • 2011-08-05
        • 2013-01-08
        相关资源
        最近更新 更多