我正在尝试将查询结果作为JSON发送,但是当我使用console.log时,它会显示空结果。
PHP代码:
function getCountries($countries){
$sql = mysqli_query($connection, 'SELECT DISTINCT id, type, level, code, name, durations FROM destinations where gateway_code="YBG" ORDER BY name' );
while($row = mysqli_fetch_array($sql))
{
echo json_encode($row); // I have doubt here, i want to send complete Query result as JSON
}
exit();
}
$abc = $_POST['countries'];
getCountries($abc);
Ajax [发送数据工作正常,但响应无效):
$(document).ready(function(){
var $leavingFrom = $('#select-leaving-from');
$leavingFrom.on('change', function() {
var $city_code = this.value;
loadDepartures($city_code);
});
});
function loadDepartures($cityname){
var dataString = $cityname;
$(document).ready(function(){
jQuery.ajax({
type: "POST",
url: 'get_data.php',
datatype: 'json',
data: {'countries': dataString},
success: function (output, textStatus) {
console.log(output);
}
});
});
}
唯一的问题是我无法将JSON数据(查询结果)发送回Ajax。需要建议
答案 0 :(得分:1)
您正在输出无效的JSON(好的,有效的JSON,多次,创建一个无效的JSON字符串,如果这是有道理的)。您需要构建整个数组,然后JSON对其进行编码:
$rows = array();
while($row = mysqli_fetch_array($sql))
{
$rows[] = $row;
}
echo json_encode($rows);
exit();
答案 1 :(得分:0)
我就是这样做的。
$json = [];
//Query here.
while ( $result = mysqli_fetch_array( //query ) )
{
$tmp = array(
'Prop1' => $result['Prop1Value'],
'Prop2' => $result['Prop2Value'],
'Prop3' => $result['Prop3Value'] );
array_push( $json, $tmp );
}
$jsonString = json_encode( $json );
echo $jsonString;
我使用的非常通用的布局。换掉“道具”#39;为您的数据库列和值。然后当你使用
outputArray = JSON.parse( output );
您将获得一个数组,其值可以像解析一样被引用
myProp1 = outputArray[ 0 ].Prop1 ;
希望这有助于!!!!
编辑:您使用$ result引用的Prop值,与您的数据库表列对齐,如果您调用了列' Capitals'你会用
来引用它'Capital' => $result['Capitals'],
并在之前和之后以相同的方式执行其他列。
答案 2 :(得分:0)
这可能是标题问题,请尝试更新标题:
header("Content-Type: application/json");