0

我正在使用航班搜索 api。我的问题在我的表单中,如果我将表单字段发送到 ajax 文件

var data = $('form').serialize();

我的 ajax 文件中是否有办法将 serialize() 字符串附加到我的 api url。现在我的 ajax 文件看起来像这样,虽然它可以工作,但它非常混乱,代码需要重构:

require('lib/Unirest.php'); 

if(isset($_POST['departureAirport'])){
    $customerSessionId = $_POST['customerSessionId'];
    $departureAirport = $_POST['departureAirport'];
    $destinationAirport = $_POST['destinationAirport'];
    $departureDate = $_POST['departureDate'];
    $returnDate = $_POST['returnDate'];
    $adults = $_POST['adults'];





$getdata = Unirest::get("http://test.api.theapidomain.com/airticket/v1/list.aspx?cid=N7Y5C1&customerSessionId=".$customerSessionId."&departureAirport=".$departureAirport."&destinationAirport=".$destinationAirport."&departureDate=".$departureDate."&returnDate=".$returnDate."&adults=".$adults."", array( "Accept" => "application/json" )
);

我真的很希望这样的事情:

$dataSent = //the serialized data sent
$getdata = Unirest::get("http://test.api.theapidomain.com/airticket/v1/list.aspx? + $dataSent, array( "Accept" => "application/json" )
    );

这是我的jQuery

<script type="text/javascript">
   $('#myform').submit(function(e){
         e.preventDefault();   
        var data = $('form').serialize(); 
        $.ajax({  
            type: "POST",  
            url: "ajax.php",  
            data: data,
            success: function(response){
            $("#result").html(response);
            }
    });
});
</script>
4

2 回答 2

1

将表单数据作为字符串发送

Javascript

$('#myform').submit(function(e){
    e.preventDefault();   
    $.ajax({  
        type: "POST",  
        url: "ajax.php",  
        data: {data: $('form').serialize()},
        success: function(response){
            $("#result").html(response);
        }
});

或简化使用$.post()

$('#myform').submit(function(e){
    e.preventDefault();   
    $.post("ajax.php", {data: $('form').serialize()}, function(response){
        $("#result").html(response);
    });
});

PHP

$dataSent = isset($_POST['data']) ? $_POST['data'] : NULL
$getdata = Unirest::get("http://test.api.theapidomain.com/airticket/v1/list.aspx?" . $dataSent, array( "Accept" => "application/json" ));
于 2013-08-04T19:45:44.533 回答
0
$dataSent = file_get_contents('php://input');

$getdata = Unirest::get("http://test.api.theapidomain.com/airticket/v1/list.aspx?".$dataSent, array( "Accept" => "application/json" )
    );

但这并不安全

于 2013-08-04T19:43:58.777 回答