2013-06-26 170 views
1

使用jquery处理Ajax成功回调事件的正确方法是什么?Ajax返回对象而不是数据

在我的代码中,当我运行而不是显示数据时,它警告object: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"; 

    } 
} 
+1

您的JSON格式味精,你不能比较对象的字符串。 – ccd580ac6753941c6f84fe2e19f229

+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); 
} 
+0

谢谢您的支持。我将阅读关联数组。 – user1532468

1

试试这个:

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

希望这将帮助!

+0

'msg.boxerrortext'并不总是存在,您需要对此进行解释 –

相关问题