简体   繁体   English

如何从PHP将正确的数据类型传递给Javascript

[英]How do I pass the correct data type to Javascript from PHP

I am using the jQuery post method to create a record in MySQL. 我正在使用jQuery post方法在MySQL中创建记录。 When I evaluate the output of the PHP with == , all three conditionals work properly. 当我用==评估PHP的输出时,所有三个条件都可以正常工作。 However, when I use === , the first two conditionals return false . 但是,当我使用=== ,前两个条件返回false How do I pass the correct data type to Javascript from PHP? 如何从PHP将正确的数据类型传递给Javascript?

jQuery: jQuery的:

$("#form").validate({

    submitHandler: function(form) {
        // do other stuff for a valid form
        $.post('inc/process_form.php', $("#form").serialize(), function(data) {
            //alert(data);
            if (data == 1) {
                $('#results').html("Success");
            } else if (data == 2) {
                $('#results').html("No Success");
            } else {
                $('#results').html(data);
            }
        });
    }
});

This is the PHP (which I've truncated to only show the execute conditional): 这是PHP(我已将其截短以仅显示执行条件):

$value = $stmt->execute();

if ($value === TRUE) {
echo 1; //success
} else {
echo 2; //failure
}

try this: 尝试这个:

if(parseInt(data) === 1){

The problem is the return variable data is a string, you can't do anything (as far as I know) from PHP to return it as a integer. 问题是返回变量data是一个字符串,您不能做任何事情(据我所知),PHP会将它作为整数返回。

As the comment by Marc Costello suggested, this makes the === useless since you are forcing both sides to be integer, so data == 1 is better in this case. 正如Marc Costello的评论所建议的那样,这使===变得毫无用处,因为您将两端都强制为整数,因此在这种情况下data == 1更好。

I never needed something like this but if you really have to you can simply cast it using +data : 我从不需要这样的东西,但是如果确实需要,可以使用+data

data = +data;
if (data === 1) {
     $('#results').html("Success");
} else if (data === 2) {
     $('#results').html("No Success");
}

在这种情况下,您可以传递布尔值而不是0或1,即php中的true或false

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM