【问题标题】:Problems accessing data from jQuery “serialize()” form to PHP backend将数据从 jQuery“serialize()”表单访问到 PHP 后端时出现问题
【发布时间】:2015-12-13 06:53:57
【问题描述】:

我正在尝试使用 jQuery serialize() 将值从动态表单传递给 PHP,但我只接收到部分字符串:

表单由 MySQL 查询创建:

echo '<form role="form" id="reserva_tour" action="shop_wopt.php" method="POST">';
 $db->Consultar("SELECT * FROM tour_options WHERE tourID = '$tour_id' order by tourID");    
while($row = $db->ObtenerArray()) {
    $regis   = $row['recid'];
    $name    = $row['name'];
    $radl    = $row['adl_rate'];
    print "<a href='#' class='tit_tour btn btn-success'>$name - $$ratebase</a>";
    print "<input type='text' name='open_adl[$regis]' id='adl$regis'  class='adl' />";
  }
  print "<a href='#' class='calcTourOpt btn btn-block">Tour Calc </a>";
  print "</form>";

jQuery:

$(".calcTourOpt").click(function()
  {
      var adl = $('.adl').serialize().replace(/%5B/g, '[').replace(/%5D/g, ']');
      console.log(adl);
      $.ajax({
         url: "calctour_opt.php",
         data:"adl=" + adl + "", 
         type: "POST",
         dataType: "json",
         cache: false,
         success: function(data){
            console.log(data)
         }  
      });
    });

这是calctour_opt.php

$adl   = $_POST['adl'];
$values = array();
parse_str($adl);   
$total = $open_adl[4]; 
echo json_encode($total);

这正在发生:

在序列化“adl”类之后(在 ajax 调用之前,在 console.log 中),字符串看起来像这样:open_adl[4]=2&amp;open_adl[5]=3 并且是正确的!

如果我在我的 php 文件中声明 $total = $open_adl[4]; 工作正常,它会显示结果:2

但如果我更改为:$total = $open_adl[5]; 不起作用,它会显示NULL,而不是3

谁能告诉我怎么了?

【问题讨论】:

  • 另一个愚蠢的问题:如何在 Ajax 调用上运行 print_r($open_adl)。如您所见,我将表单发送到 Jquery,然后我进行了 Ajax 调用?

标签: php jquery ajax serialization


【解决方案1】:

您应该像这样将 $.ajax data 参数从 string 更改为 json 字符串

// FROM 
$.ajax({
     url: "calctour_opt.php",
     data:"adl=" + adl + "", //<- Wrong
     type: "POST",
     ...

// TO
$.ajax({
     url: "calctour_opt.php",
     data: {adl: adl}, //<- Correct

在此处查看有关 data ajax 参数的文档 - http://api.jquery.com/jquery.ajax/

【讨论】:

  • 我将表单输入作为类 'adl' $('.adl') 发送到 Jquery,然后我使用变量 adl 数据进行了 ajax 调用:"adl=" + adl + ""
猜你喜欢
  • 2020-05-07
  • 2012-09-10
  • 2012-04-24
  • 1970-01-01
  • 1970-01-01
  • 2019-03-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多