javascript 我什么时候应该向 AJAX 返回真/假,什么时候我应该回显“真”/“假”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14708269/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
When should I return true/false to AJAX and when should I echo "true"/"false"
提问by K.K. Smith
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 returning true/false. I see now that is not the case, but can someone break it down for me?
不知何故,我想到了当用 AJAX(如 $.post)访问 PHP 时,你必须回显“真”或“假”而不是返回真/假。我现在看到情况并非如此,但有人可以为我分解吗?
Is it that there is a problem testing a boolean? Like here
测试布尔值是否存在问题?像这儿
...
$.post('ajax/doThing',{data: data},
function(response) {
if(response) {
doThis();
}else{
doThat();
}
That is the problem case, correct? Here I cannot return true/false, instead I must echo back a string and test the string, yes?
这就是问题所在,对吗?在这里我不能返回真/假,而是我必须回显一个字符串并测试该字符串,是吗?
if(response === "true")
But I have seen boolean true/falses returned to ajax functions. What is the use of this, if you cannot test a boolean on the AJAX side? And why can't ajax test a boolean?
但我已经看到布尔真/假返回到 ajax 函数。如果您无法在 AJAX 端测试布尔值,这有什么用?为什么 ajax 不能测试布尔值?
Or am I still confused?
还是我还在迷茫?
EDIT
编辑
Just wanted to thank everyone for their good answers on this. I am now +2 smrter.
只是想感谢大家对此的好回答。我现在+2 smrter。
回答by T.J. Crowder
You might also look at returning HTTP error codes rather than returning a "success" response (HTTP status code 200) when the request wasn't really successful, and then use an error
callback to handle unsuccessful requests.
当请求不是真正成功时,您还可以查看返回 HTTP 错误代码而不是返回“成功”响应(HTTP 状态代码 200),然后使用error
回调来处理不成功的请求。
But if you want to keep using status code 200 (and a lot of people do that):
但是,如果您想继续使用状态代码 200(并且很多人都这样做):
The data transferred between the client and the server is alwaystext. The trick is to make sure that the client and server agree on how the client should deserialize the text (transform it upon receipt). Typically you might return one of four things:
客户端和服务器之间传输的数据始终是文本。诀窍是确保客户端和服务器就客户端应如何反序列化文本(在收到时对其进行转换)达成一致。通常,您可能会返回以下四种情况之一:
HTML (if it's going to populate page elements)
JSON (if you want a lightweight, fast way to send data to the client)
XML (if you want a heavier-weight, fast way to send data to the client)
Plain text (for whatever you want, really)
HTML(如果要填充页面元素)
JSON(如果您想要一种轻量级、快速的方式将数据发送到客户端)
XML(如果您想要一种更重、更快速的方式将数据发送到客户端)
纯文本(无论你想要什么,真的)
What the client does will depend on what Content-Type
header you use in your PHP page.
客户端做什么将取决于Content-Type
您在 PHP 页面中使用的标头。
My guess is that you're using any of several content types that end up passing on the data as a string to your callback. The string "true"
is truthy, but so is the string"false"
(only blank strings are falsey).
我的猜测是您正在使用几种最终将数据作为字符串传递给回调的内容类型中的任何一种。该字符串"true"
是truthy,但这样是字符串"false"
(仅空字符串falsey)。
Long story short: I'd probably use this in my PHP:
长话短说:我可能会在我的 PHP 中使用它:
header('Content-Type', 'application/json');
...and the return this text from it:
...并从中返回此文本:
{"success": true}
or
或者
{"success": false}
...and then in your success handler:
...然后在您的成功处理程序中:
if (response.success) {
// It was true
}
else {
// It was false
}
Alternately, you can return a Content-Type
of text/plain
and use
或者,你可以返回Content-Type
的text/plain
和使用
if (response === "true") {
// It was true
}
else {
// It was false
}
...but that's kind of hand-deserializing where you could get the infrastructure to do it for you.
...但这是一种手动反序列化,您可以在其中获得基础架构来为您执行此操作。
回答by Ja?ck
Your script should either return a response that translates into a JavaScript equivalent of your PHP variables to make such comparisons possible oruse HTTP status codes to convey an error condition.
您的脚本应该返回一个响应,该响应转换为与您的 PHP 变量等效的 JavaScript,以使此类比较成为可能,或者使用 HTTP 状态代码来传达错误条件。
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.
jQuery.ajax()
和朋友根据您发送的响应标头(XML、JSON 等)解释响应(默认情况下自动)。
The below code outputs a JSON formatted response:
下面的代码输出一个 JSON 格式的响应:
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.:
jQuery.ajax()
还可以处理除常规之外的 HTTP 状态代码响应200 OK
,例如:
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');
}
});
回答by phpalix
Ajax calls expects a text returned by your scripts, when you return a php bool, it will not be outputted, so you need to echo "something", and its does not have to be "true" or "false"
Ajax调用需要你的脚本返回一个文本,当你返回一个php bool时,它不会被输出,所以你需要echo“something”,它不必是“true”或“false”
回答by Bergi
All depends on your server response. If you use appropriate MIME types, jQuerymight automatically JSON.parse()
the response for you, passing the boolean true
to your callback. If it does not recognize JSON, it will pass the textual result "true"
which you need to compare against:
一切都取决于您的服务器响应。如果您使用适当的 MIME 类型,jQuery可能会自动JSON.parse()
为您响应,将布尔值传递true
给您的回调。如果它不能识别 JSON,它将传递"true"
您需要与之比较的文本结果:
// PHP:
header('Content-Type', 'application/json');
echo true; // or "true" or json_encode(true)
// JavaScript (with jQuery.ajax):
… function callback(response) {
typeof response; // "boolean"
if (response) {…}
} …
// PHP:
header('Content-Type', 'text/plain'); // or similar, also implicit
echo "true";
// JavaScript (with jQuery.ajax):
… function callback(response) {
typeof response; // "string"
if (response == "true") {…}
} …