简体   繁体   中英

return javascript error via cakephp

$.ajax({
                    type: "POST",
                    url: "/find",
                    data: {coupon_name:value},
                    success: function(response) {
                        alert("success")
                    },
                    error: function(xhr, ajaxOptions, thrownError) {
                        alert(thrownError);

                    }
                });

What do I "echo" within my PHP page to throw an error? Basically I'm using the ajax function to count the number returned, if <1 it needs to throw an error back to the JS.

The jQuery specification defines .error() as:

A function to be called if the request fails.

A failure HTTP code is one in the 400s or 500s, so a CakePHP equivalent of:

<?php
    http_response_code(500);
?>

should trigger it.

That said, I'm not sure that throwing an error is necessarily correct in your circumstances - your query hasn't actually errored, it just has returned zero results. So you may be best handling this within the .success() function anyway.

I suggest you leave the error for the real HTTP-related emergencies, and handle your code logic in your response. The easiest approach is making the response into JSON, returning an error component in the JSON if you encounter an error, and manually checking for its presence.

That said, you can use $this->controller->response->statusCode(400) (in CakePHP) or similar to send a status code that will trigger an error clause. But I recommend against it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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