我正试图使用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&open_adl[5]=3
,并且是正确的!
在我的php文件中,如果我声明$total = $open_adl[4];
工作正常,它会显示结果:2
。
但如果我改为:$total = $open_adl[5];
不起作用,它会显示NULL
,而不是3
。
有人能告诉我怎么了吗?
您应该将$.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
查看这里的文档关于ajax的data
参数-http://api.jquery.com/jquery.ajax/