When should I return true/false to AJAX and when should I echo “true”/“false”

前端 未结 4 1321
忘掉有多难
忘掉有多难 2020-12-16 08:17

Somehow I have confused myself.

Somehow I got it in my head that when hitting PHP with AJAX (like $.post), you had to echo back a \"true\" or \"false\" instead of re

4条回答
  •  轮回少年
    2020-12-16 09:04

    Your script should either return a response that translates into a JavaScript equivalent of your PHP variables to make such comparisons possible or use HTTP status codes to convey an error condition.

    Response handling

    jQuery.ajax() and friends interpret the response (automatically by default) based on the response headers that you send, be it XML, JSON, etc.

    The below code outputs a JSON formatted response:

    header('Content-Type: application/json');
    echo json_encode(array(
        'success' => true,
    ));
    

    The output that is sent to the browser looks like this:

    {"success": true}
    

    Inside your success handler you can now use the following code:

    if (response.success) { ... }
    

    Error handling

    jQuery.ajax() can also handle HTTP status code responses other than the regular 200 OK, e.g.:

    header('404 Not found');
    exit;
    

    This will invoke your error handler:

    $.ajax({
        url: ...,
        error: function(xhr, status, msg) {
          // xhr - see http://api.jquery.com/jQuery.ajax/#jqXHR
          // status - "error"
          // msg - "Not found"
          alert('Error code ' + xhr.code + ' encountered');
        }
    });
    

提交回复
热议问题