AJAX:使用单个变量发送各种数据

时间:2017-12-12 11:34:12

标签: php ajax

我有以下代码,使用post方法将一系列数据发送到另一个php页面。

$(document).ready(function(){  
  $('#min_price').change(function(){  
    var price = $(this).val(); 
    var codehotelstring = (<?php echo $impl_selez_hotel ?>); 
       $("#price_range").text("Product under EUR." + price);  
       $.ajax({  
            url:"/loading-price-range.php",  
            method:"POST",  
            data: {price: price, codehotelstring: codehotelstring},  
            success:function(data){  
                 $("#product_loading").fadeIn(500).html(data);  
            }  
       });  
  });  
 });   

该脚本定期运行,但我遇到的问题是“codehotelstring”变量只发送一系列数据中的最后一个,取自mysqli查询。 数据字符串如下:

"1071bf", "107155", "114c25", "137521", "15baf7", "19d7f9", "10b280", "19f2fa", "110bfb", "1106eb", "1398c4 "," 1071b8 "," 107124 "," 1071c7 "," 19d97b "," 16d78f "," 10727b "," 107127 "," 10aab6 "," 193e62 "," 110bf5 "," 107126 "," 189b95 ", "107357", "10731e", "107061", "114e7a", "19d938", "107078", "1070a2", "1070a3", "107af1", "1070a7", "107311".

通过在着陆页上执行"print_r ($ _POST ['codehotelstring']);",显示的结果为“107311”。

我还试图对使用$ _POST ['codehotelstring']获得的数据执行foreach,但没有解决问题。

2 个答案:

答案 0 :(得分:1)

在javascript中。

 var first_name = 'stack'; // you can also use jquery or javascript here to get the value of id;
 var last_name = 'overflow';
 var postForm = { 
                'firstname':first_name ,

                'lastname': last_name

              };

 $.ajax({url:localhost/index.php, 
                       type: "POST",
                       data: postForm, //Forms name

                       error: function (xhr, status)
                                       {
                               //Error message
                                       },
                        success: function(msg)
                         {
                            //response of the server
                              alert(msg);
                         }
                 });

在index.php中

$firstname = $_POST["firstname"];
$lastname = $_POST["lastname"];
echo($firstname.$lastname); //this echo result will be displayed as response from the server

答案 1 :(得分:0)

尝试在将$impl_selez_hotel发送到服务器之前对其进行json编码,如下所示:

var codehotelstring = "<?php echo json_encode($impl_selez_hotel); ?>";

然后你可以json解码服务器端:

$decodedData = json_decode($_POST['codehotelstring']);

请注意,这不是经过测试的代码,我只是通过内存编写:)