使用 jquery 处理 Ajax 成功回调事件的正确方法是什么?
在我的代码中,当我运行而不是显示数据时,它会警告对象:对象。但是,如果我使用 msg.box
它会正确返回数据。
我正在尝试创建一个 if
语句,其中 如果文本等于某个单词
,则 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";
}
}
最佳答案
在 JavaScript 中,关联数组称为对象,因此传输的数据不会出现错误。
为什么将msg
与“您需要输入一个框”
进行比较?您无法比较对象和字符串,这没有意义。
if(typeof msg.boxerrortext !== "undefined" && msg.boxerrortext == "You need to input a box") {
$("#BA_addbox").html(msg.boxerrortext);
} else {
$("#BA_addbox").html(msg.box);
}
关于php - Ajax 返回对象而不是数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17326228/