开发者

AJAX/JQuery success:/error: function manipulation

Having some trouble with AJAX/JQuery. Here is the context of my problem followed by a code sample:

What I am attempting to do is call a PHP script called getInfo.php and check whether or not some data is contained within a database. I can write queries easily enough but in terms of the code sample below how can I "tell" the success function to fail if it cannot find data in the database and run the error function instead?

$(document).ready(function(){
        getInfo();
        function getInfo(){
            $.ajax({
                type: "GET",
                url: "getInfo.php",
                data: "do=getInfo",
                cache: fal开发者_如何学JAVAse,
                async: false,
                success: function(result) {
                    $("#myInfo").remove();
                    alert("Data found");
                },
                error: function(result) {
                    alert("Data not found");
                }
            });
        }
});

Any advice would be greatly appreciated. =)


The error handler is used to handle errors in your AJAX call.

You could echo 1 in your PHP script if the data was found and 0 if it was not found. Then you could use an if statement to determine what to do. For example:

success: function(result)
{
    if(result == 1)
    {                    
        $("#myInfo").remove();
        alert("Data found");
    }
    else
    {
        alert("Data not found");
    }
},


"success" gets called when the returned code is a "200" (successfull request). "error" gets called whenever another code is returned (e.g. 404, 500).

So I think you can do 2 things:

  • Let PHP return a 404 so the error function gets called
  • Let your getinfo.php return a boolean value (usually my approach)

    {"success":true, ...}


The 'error' function you're using is for identifying and handling an AJAX error, not a script error. If the script you're calling is found, and it executes without terminating unexpectedly (ie, it has errors!), then its considered a success.

The best thing to do is have your getInfo.php script return something you can use within the success function; such as the number of rows in your result set or something - then you can check in success() whether you have data and code accordingly.


I think your getInfo.php page should just print SUCCESS or FAIL and in your success method do

success: function(result) {
        if (result == 'SUCCESS')
        {
          $("#myInfo").remove();
          alert("Data found");
        }
        else
        {
          alert("Data not found");
        }
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜