jQuery JSON未返回值

3
我正在使用jQuery通过序列化提交表单,一切都很好,除非我输入超过1个框。如果我只输入1个框,则msg.box会出现在#BA_addbox中。但是,如果我使用逗号作为分隔符输入多个框,则不会显示任何消息,并且在Firebug中不会出现JSON选项卡,只有正确的HTML。我的代码哪里出了问题?
我已经创建了一个数组,并使用foreach和explode来分离值,但没有返回多个值。谢谢。
更新:变量在php脚本中被收集,如下所示:
$dept = mysql_real_escape_string($_POST['customerdept']);
$company = mysql_real_escape_string($_POST['BA_customer']);
$address = mysql_real_escape_string($_POST['customeraddress']);
$service = mysql_real_escape_string($_POST['BA_service']);
$box = mysql_real_escape_string($_POST['BA_box']);
$date = DateTime::createFromFormat('d/m/Y', $_POST['BA_destdate']);
$destdate = $date - > format('Y-m-d');
$authorised = mysql_real_escape_string($_POST['BA_authorised']);
$submit = mysql_real_escape_string($_POST['submit']);

$array = explode(",", $_POST['BA_box']);

     if (isset($_POST['submit']))   {
        foreach ($array as $box) {

        //$sql = "INSERT INTO `act` (service, activity, company, address, department, user, destroydate, date, item, new) VALUES ('$service', '$activity', '$company', '$address', '$dept', '$authorised', '$destdate', NOW(), '$box', 1)";
        //$result = runSQL($sql) or die(mysql_error());

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

        echo $result;


   } 
  }

jQuery代码

submitHandler: function()   {
                if ($("#BA_boxform").valid() === true)  { 
                var data = $("#BA_boxform").serialize();
                $.post('/domain/admin/requests/boxes/boxesadd.php', data, function(msg) {
                $("#BA_addbox").html("You have entered box(es): " + "<b>" + msg.box + "</b><br /> You may now close this window.");
                $("#BA_boxform").get(0).reset();
                }, 'json');

         } else

         { 
           return; 
         }
        },
        success:    function(msg)   {
                //$("#BA_addbox").html("You have entered a box");
                //$("#BA_boxform").get(0).reset();
        }   

3
如果你的PHP循环处理多个项目,那么你生成的JSON响应就是无效的,因为它会依次输出多个JSON片段(这些片段不能组成一个大的JSON字符串)。你需要使用循环来创建一个包含所有数据的数组,然后在循环之后使用json_encode()函数。 - nnnnnn
@PLB 谢谢你的回复,但是这怎么能帮助我解决我的问题呢? - user1532468
@user1532468,我并不是想要解决这个问题。我只是提醒您而已。 ;) 在我看来,当您发现有什么问题时,重要的是不要袖手旁观。 - Leri
请在 echo $result; 之前添加代码 header('Content-Type: application/json'); - softsdev
@softsdev 仍然收到空消息。谢谢。 - user1532468
显示剩余4条评论
2个回答

1

首先修复PHP代码,使其返回一个有效的JSON数组。

if (isset($_POST['submit']))   {
  foreach ($array as $box) {

    //$sql = "INSERT INTO `act` (service, activity, company, address, department, user, destroydate, date, item, new) VALUES ('$service', '$activity', '$company', '$address', '$dept', '$authorised', '$destdate', NOW(), '$box', 1)";
    //$result = runSQL($sql) or die(mysql_error());

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

  }
  echo json_encode( $result );
}

那么在post回调中的msg参数应该是结果数组,因此您不能仅使用msg.box来获取箱子列表。我建议像这样:

boxes = jQuery.map(msg,function(item){
  return item.box;
}).join(',');

从数组中提取每个项目的框属性,并将它们连接成逗号分隔列表。然后,您可以像这样显示该列表:
$("#BA_addbox").html("You have entered box(es): " + "<b>" + boxes + 
  "</b><br /> You may now close this window.");

根据这些更改,您的代码对我有效。如果您遇到其他问题,建议您发布更多的HTML - 特别是表单结构。可能您的表单未提交正确的值以从服务器获得有效响应。


我遇到了一个错误:在jquery.js中,length = elems.length。我已经创建了一个fiddle来展示我正在使用的代码。你能帮我检查一下错误吗?谢谢 http://jsfiddle.net/T2NuC/1/ - user1532468
你的php代码缺少一条语句结尾的分号:$result[]=$form。另外,你需要为变量$dept、$company、$address等赋值。我建议你最初先硬编码一些字符串。 - James Holderness
你还没有初始化$submit变量。此外,你应该知道如果你没有使用mysql_connect打开数据库连接,mysql_real_escape_string是无法工作的。我也不确定为什么你要在json对象中返回的值上调用它 - 只有在你将这些值用于数据库查询时才有意义。 - James Holderness
James,我正在进行数据库查询,只是没有在代码中显示。我的代码中有:$submit = mysql_real_escape_string($_POST['submit']); 我已经更新了OP的代码。你能否举个例子解释一下我如何初始化$submit变量,因为我对jquery还比较新手。我已经在fiddle中更新了代码。http://jsfiddle.net/T2NuC/3/ 谢谢 - user1532468
我在你展示给我的当前PHP代码中仍然能够看到一个明显的错误,即对$date - > format的调用。->之间不应该有空格。正确的写法是$date -> format - James Holderness
显示剩余2条评论

1

根据 @nnnnnn 的说法:

如果有多个框,您的JSON结果将如下结构所示。这是无效的JSON,因此无法可靠地解析。

{
  ...
}{
  ...
}

为了解决这个问题,您需要将这些数组添加到另一个数组中,然后对父数组进行编码。
$box = mysql_real_escape_string($_POST['BA_box']);
$array = explode(",", $_POST['BA_box']);
$output = Array();

if (isset($_POST['submit']))   {
  foreach ($array as $box) {

    //$sql = "INSERT INTO `act` (service, activity, company, address, department, user, destroydate, date, item, new) VALUES ('$service', '$activity', '$company', '$address', '$dept', '$authorised', '$destdate', NOW(), '$box', 1)";
    //$result = runSQL($sql) or die(mysql_error());

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

    //Add to a parent array instead
    $output[] = $form;

  }

  //encode the entire array
  $result = json_encode( $output );

  echo $result;
}

这将导致以下结构,对于包含解析json的变量data,每个框可以通过data [0] data [1] 等进行检索。
[  {    ...  },  {    ...  }]

请问您能为我解释一下 data[0] 的代码吗?根据我的原始代码,我该如何检索值呢?谢谢。 - user1532468
我不知道你想要显示什么。在你的javascript中:data[0]将返回第一个框的结构(例如,在你的php脚本中放置的内容)。data.length返回发送回来的框的数量。 - Sumurai8

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接