PHP和AJAX:如何发送/处理错误的反应?反应、错误、PHP、AJAX

2023-09-11 22:28:43 作者:喜疾

有3个元素这一点。

在一个HTML表单 在阿贾克斯的连接,它发送表单值并接收和分析从PHP脚本响应 在该决定的值是否是好/坏与否,并发送回一个适当的响应的PHP脚本(可能为便于分析由JavaScript函数XML格式?)

在PHP看及处理发送的数据,将其插入到数据库或做什么用的,它需要发回一个响应或者反应可能是集合使JavaScript可以显示正确的错误消息(S)给用户。也许也把一个红色的边框或周围的东西有坏输入的元素。

When the PHP looks at and handles the sent data, inserting it into a database or doing whatever with it, it needs to send back a response or maybe a collection of responses so that javascript can display a proper error message(s) to the user. Maybe also putting a red border or something around the elements that have the bad input.

这是怎么通常是,在两端的?我在想,PHP应该只是发回简单的数字错误codeS和JavaScript将在不同的div设置适当的文本错误信息。但我真的不知道,我真的不知道我应该使用Google来寻找答案。

How is this usually done, on both ends? I'm thinking that PHP should just send back simple numeric error codes and javascript will set the proper text error messages in different divs. But I'm not really sure, and I'm not really sure what I should be googling to find an answer.

(顺便说一句,我不是在谈论C $ CS HTTP错误$)

(BTW I'm not talking about HTTP error codes)

推荐答案

你所要求被称为验证。 有服务器端验证和客户端验证。

What you are asking is called validation. There is server side validation, and client side validation.

首先是最重要的,因为你不希望用户损坏您的数据库。 二是为您的客户很重要。因为它给他任何事情迅速作出反应这是与形式(红色边框)。

The first is the most important one, as you don't want users to corrupt your database. The second is important for your customer. As it gives him prompt response about anything that's invalid with the form (red border).

如果您想验证表单客户端,它通常是使用JavaScript。 对于服务器端验证,我会用JSON,为服务器和客户机之间的通信,因为这两个PHP和JavaScript知道如何应付自如。

If you want to validate the form client side, it is usually done with Javascript. For server side validation, I would use JSON, as the communication between server and client, as both php and javascript know how to handle it well.

有关PHP: http://php.net/manual/en/function.json -en code.php http://php.net/manual/en/function.json -de code.php

For php: http://php.net/manual/en/function.json-encode.php http://php.net/manual/en/function.json-decode.php

有关JS。 刚刚访问结果参数:

for JS. just access the result parameter:

   success: function(response){
        var json = $.parseJSON(response.responseText);
   }