从jQuery的阿贾克斯布尔参数收到的文字串QUOT;假" /"真"在PHP [英] Bool parameter from jQuery Ajax received as literal string "false"/"true" in PHP

查看:123
本文介绍了从jQuery的阿贾克斯布尔参数收到的文字串QUOT;假" /"真"在PHP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此问题与有关:

<一个href="http://stackoverflow.com/questions/2794183/cannot-pass-null-to-server-using-jquery-ajax-value-received-at-the-server-is-the">Cannot传递null使用jQuery AJAX服务器。在服务器接收到的值是字符串&QUOT;零&QUOT;

不过,我再次问,因为在这个问题的解决是非常难看的,我想一定是一个更好的。

But I'm asking it again because the solution in that question is very ugly, and I think must be a better one.

问题
当您使用发送数据与jQuery阿贾克斯PHP POST你得到的字符串,而不是假(布尔)假(串),而不是NULL,真正的,而不是真正的(布尔)和空:

PROBLEM
When you send data with jQuery Ajax to PHP using POST you get strings "false"(string) instead of false(bool), "true" instead of true(bool) and "null" instead of NULL:

解决方案:
(在上面的问题提出的): 之前的数据转换为JSON它使用jQuery发送,然后去code在PHP中的数据。 随着code:

SOLUTION
(proposed in the above question): convert the data to JSON before send it with jQuery, and then decode that data in PHP. With code:

Javascript的code:

Javascript code:

$.ajax
(
   {
      url     : <server_url>,
      dataType: 'json',
      type    : 'POST',
      success : receiveAjaxMessage,
      data    : JSON.stringify
      (
         {
            valueTrue : true,
            valueFalse: false,
            valueNull : null
         }
      )
   }
);

PHP code:

PHP code:

var_dump(json_decode(file_get_contents('php://input'), true));

要我说,这不是一个解决方案,只是一个丑陋的黑客。

To me that's not a solution, only an ugly hack.

在我的情况的问题是,我不能使用的file_get_contents('php的://输入)来访问$ _ POST,甚至更多,我不能用$ _ POST,因为我使用HMVC

The problem in my situation is that I can't use file_get_contents('php://input') to access the $_POST, even more, I can't use $_POST because I'm using HMVC.

和我知道我可以修复它​​检查那些假,真和空在PHP中,或发送1和0 instear真假jQuery的。照片 不过,我想这一定是一个非常普遍的问题,和jQuery是一个非常共同的框架,所以我pretty的肯定有一个更好,优雅的方式来将数据与正确的类型jQuery中发送。

And I know I can fix it checking those "false", "true" and "null" in PHP, or sending 1 and 0 instear true and false in jQuery.
But I think this must be a really common problem, and jQuery is a really common framework, so I'm pretty sure there's a better and elegant way to send the data with the right type in jQuery.

推荐答案

由于HTTP是布尔值的概念文本协议或整体都必须字符串化。在服务器端比较字符串是正常的方法来处理布尔值。

Because HTTP is a text protocol with no concept of booleans or integers everything must be stringified. Comparing strings on the server side is the normal way to deal with booleans.

如果你真的想要的PHP看0或1,你可以使用

If you really really want PHP to see a 0 or 1 you can use

 valueTrue : true ? 1 : 0

在你的AJAX调用。

这篇关于从jQuery的阿贾克斯布尔参数收到的文字串QUOT;假&QUOT; /&QUOT;真&QUOT;在PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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