Ajax返回对象而不是数据

时间:2013-06-26 17:02:36

标签: php jquery ajax

使用jquery处理Ajax成功回调事件的正确方法是什么?

在我的代码中,当我运行而不是显示数据时,它会提醒对象:object。但是,如果我使用说msg.box,它会正确返回数据。

我正在尝试创建if语句,其中if text equals a certain word然后json中的变量放在结果div BA_addbox的html中。

我似乎无法让这个工作,如果有人能指出我的错误,我将不胜感激。我只包含了相关代码,因为表单正在发布正确的数据,而php代码正在捕获所有帖子。非常感谢。

ajax代码

$.ajax({
    type: "POST",
    url: "/domain/admin/requests/boxes/boxesadd.php",
    data: formdata,
    dataType: 'json',
    success: function(msg){
        if(msg == "You need to input a box") {
            $("#BA_addbox").html(msg.boxerrortext);
        }
        else {
            $("#BA_addbox").html(msg.box);
        }

        //alert(msg);
        console.log(msg);
        //$("#BA_addbox").html(msg.box);

        //$("#formImage .col_1 li").show();
        //$("#BA_boxform").get(0).reset();
        //$("#boxaddform").hide();
    }
});

boxesadd.php

$box = mysql_real_escape_string($_POST['BA_box']);
$boxerrortext = "You need to input a box";

if (isset($_POST['submit']))    {
    if (!empty($box)) {

        $form = array('dept'=>$dept, 'company'=>$company, 'address'=>$address, 'service'=>$service, 'box'=>$box, 'destroydate'=>$destroydate, 'authorised'=>$authorised, 'submit'=>$submit);

        $result = json_encode($form);

        echo $result;

    }
    else
    {

        $error = array('boxerrortext'=>$boxerrortext);

        $output = json_encode($error);

        echo $output;
        //echo "You need to input a box";

    }
}

2 个答案:

答案 0 :(得分:4)

在javascript中,关联数组被称为对象,因此传输的数据中没有错误。

为什么要将msg"You need to input a box"进行比较?你无法比较对象和字符串,这没有任何意义。

if(typeof msg.boxerrortext !== "undefined" && msg.boxerrortext == "You need to input a box") {
    $("#BA_addbox").html(msg.boxerrortext);
} else {
    $("#BA_addbox").html(msg.box);
}

答案 1 :(得分:1)

请改为尝试:

if(msg.boxerrortext) {
  $("#BA_addbox").html(msg.boxerrortext);
}
else {
  $("#BA_addbox").html(msg.box);
}

希望这会有所帮助!!