使用die()返回PHP中的Ajax值 [英] Using die() to return ajax value in PHP

查看:206
本文介绍了使用die()返回PHP中的Ajax值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有任何理由不使用die($result)返回PHP中的Ajax请求结果?请注意,这是关于代码语义的理论问题.

Are there any reasons to not to use die($result) to return Ajax request result in PHP? Please note that this is theoretical question, about code semantics.

简单的示例(当然,函数可能会复杂得多,并返回不同的值).

Simple example (of course functions may be much complicated and return different values).

JS:

<script>
   function checkLogin(login){
      $.post('/ajax/check',{'login':login},function(res){
          if(res == 1) return 1; else return 0;
      }
   }
</script>

PHP:

<?php
   $db = mysql_connect(...);
   $login = mysql_real_escape_string(stripslashes($_POST['login']));
   $res = mysql_query("SELECT * FROM project.users WHERE login = '$login'");
   if(mysql_num_rows($res)) die('0'); else die('1');
?>

PS.我知道mysql_*()函数已被弃用,无需对此发表评论.我只是喜欢使用它们,并且会.在可能的范围内.

PS. I know tha that mysql_*() functions are deprecated, no need to comment that. I simply like using them and will. As far as it will be possible.

我想知道为什么没有人注意到checkLogin()函数没有意义,因为请求是异步的,并且函数总是返回undefined;-)

I wonder why noone noticed that checkLogin() function has no sense, as request is async, and function always returns undefined ;-)

推荐答案

由于die()不会发送任何HTTP错误状态,因此使用它返回ajax调用的字符串没有问题,但是仍然存在可以这样说,对于代码的可读性,我认为这不是一个好主意,但是除此之外,对于功能而言,它没有问题,因为它可以输出消息. 而且,也就是说,您必须考虑CLI PHP之类的情况,在这种情况下,返回的整数确实对shell有意义(仅供参考).

Since die() does not send any HTTP error status, there is no problem using it to return a string for an ajax call, but what stays there to say is, for the readability of the code, I don't think it's a good idea, but other than that, for functionality, there is no problem with it,since it outputs the message. but also, now that's it's said, you have to take into consideration cases like CLI PHP in which the returned integer can really mean something for the shell(just for mentioning).

这篇关于使用die()返回PHP中的Ajax值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆