关于php中的函数的问题

时间:2011-04-11 18:50:03

标签: php javascript jquery ajax

我有一个带有两个功能的php文件

<?php 

function first () {
//in real case more conditions
echo "first";
return true;
}

function second () {
//in real case more conditions
echo "second";
return true;
}

first();
second();

?>

并在ajax文件中

function(data) {
                if (data == "first") {
                    $("#msgbox1").fadeTo(200, 0.1, function() {
                        $(this).html('something');
                    });
                } 
                else if (data == "second") {
                    $("#msgbox1").fadeTo(200, 0.1, function() {
                        $(this).html('Something else');
                    });
                } 

问题是因为php首先下载并且我需要检查个人模式 - 第一和第二。如果我先退货;如果返回正确,我如何检查数据? data ==首先不工作

感谢

1 个答案:

答案 0 :(得分:5)

你需要更多的东西:

function first() {
    if (some condition ...) {
       return true;
    }
    return false;
}

function second() {
   if (some other condition...) {
      return true;
    }
    return false;
}

$data = array();

$data['first'] = first();
$data['second']= second();

echo json_encode($data);

然后在您的Javascript代码中:

if (data.first) {
   ... first occurred
}
if (data.second) {
   ... second occured;
}

最好通过JSON编码返回实际的Javascript数据结构,而不是字符串。这样您就可以传入其他数据元素。例如,如果first()正在进行数据库查找并且发生了某些事情,则可以返回“false”以及指示请求失败原因的错误消息。

相关问题