php - Ajax 返回对象而不是数据

标签 php jquery ajax

使用 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/

相关文章:

javascript - 使用 SQLite 和 Flask 搜索自动完成

php - 我将使用哪些 PHP 函数结合 AJAX/无限滚动来加载 WordPress 网站的页面?

php - 未定义索引 PHP Ajax jquery post

php - mysql中的计数语法

javascript - 自定义用户 HTML 输入安全

具有动态类名的 PHP 命名空间

javascript - ajax 忽略 url

javascript - 在 Symfony2 中使用 Typeahead + Bloodhound 和 FOSJsRoutingBundle 执行查询

javascript - 动态改变 CSS 类

php - 使用 PHP 简单 HTML DOM 将隐藏的输入标签值作为字符串获取