来自REST API的jQuery Post Callback

I am working on an app that will submit data to a REST API and have some questions.

  1. How does jQuery know if my post request was successful or not? Is it only looking at the HTTP status?

  2. Is there a convention on what to return from a POST request to a REST API?

JavaScript

$.post( '/API/removeUser', { Eid: id }, function(data) { row.remove(); } );

PHP SLIM Framework

$app->POST('/API/removeUser', function () use ($app) {
    
    // Get the ID from the jQuery post                  
    $Eid = trim(stripslashes(htmlspecialchars($_POST['Eid'])));         
    
    echo json_encode(removeFunction($Eid));
    
});

</div>

1个回答



您的后端应始终返回相应的 HTTP状态代码以及实际数据。 404用于未找到的资源,403用于未授权的请求,200用于成功的请求等。大多数AJAX库(包括jQuery)将依赖于这些来确定操作的结果。</ p>

如果 您需要更细粒度的错误报告,您可以在响应中包含一个类似“errorCode”的字段,其中包含您自己定义的应用程序级错误代码,并在您的前端代码中做出相应的反应。</ p>
< / DIV>

展开原文

原文

Your backend should always return the appropriate HTTP status code along with the actual data. 404 for resources that were not found, 403 for unauthorized requests, 200 for successful requests etc. Most AJAX libraries (including jQuery) will rely on those for determining the result of the operation.

If you need more fine-grained error reporting, you could always include a field like "errorCode" in your response that contains an application-level error code that you define yourself and react to accordingly in your frontend code.

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐