我正在使用航班搜索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>
答案 0 :(得分: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" ));
答案 1 :(得分:0)
$dataSent = file_get_contents('php://input');
$getdata = Unirest::get("http://test.api.theapidomain.com/airticket/v1/list.aspx?".$dataSent, array( "Accept" => "application/json" )
);
但这不安全