【发布时间】:2014-11-13 02:17:27
【问题描述】:
我正在对一个相当简单的 PHP 函数进行 AJAX 调用。响应应该是要操作的 JSON 对象,但我的响应始终是空对象。
相关代码:
index.html 的 AJAX 调用:
$( function() {
$('#dates').on('submit', function (e) {
var start_time = new Date().getTime();
e.preventDefault();
var submitData = $('#dates').serialize();
console.log(submitData);
$.ajax({
type:'POST',
url:'inflow.php',
data:$('#dates').serialize(),
dataType: 'json',
beforeSend: function(){
$('#loading').show();
},
success: function(data) {
console.log(data);
$('#loading').hide();
},
error:function(xhr, desc, err){
alert('You tried to send an AJAX request, but something went wrong.\n Please Contact the NASR WebDev Team');
console.log(xhr);
console.log("Details: " + desc +"\nError: "+ err);
}
});
});
});
inflow.php 的数组创建和回显:
<?php
$msqlStart = $_POST['start_date'];
$msqlEnd = $_POST['end_date'];
$inflowQuery=
"SELECT
COUNT,
QUEUE_ID,
QUEUE_GROUP,
INFLOW_DATE,
LINE_OF_BUSINESS
FROM
ticket_inflow.inflow
WHERE
ROUTE_STATUS = 'Inflow'
AND inflow_date between ? and ?";
$connect = new mysqli($host, $user, $password, $database);
if ($connect->connect_error){
die("Failed to Connect:.".$connect->connect_errno.": ".$connect->connect_error);
}
if(!($statment = $connect->prepare($inflowQuery))){
die('Error in Preparation Error Number:%d Error: %s');
}
if(!$statment->bind_param('ss', $msqlStart, $msqlEnd)){
die ('Error in Binding');
}
if(!$statment->execute()){
die('Error In Execution');
}
$statment->bind_result($inflowCount, $inflowQueue, $inflowQG, $inflowDate, $inflowLOB);
$a_json = array();
$jsonRow = array();
While($statment->fetch()){
$UID = 0;
$jsonRow['UID'] = $UID++;
$jsonRow['count'] = utf8_encode($inflowCount);
$jsonRow['inflow_date'] = utf8_encode($inflowDate);
$jsonRow['queue'] = utf8_encode($inflowQueue);
$jsonRow['queue_group'] = utf8_encode($inflowQG);
$jsonRow['lob'] = utf8_encode($inflowLOB);
array_push($a_json, $jsonRow);
}
$jsonReturn = json_encode($a_json);
echo $jsonReturn;
?>
如果我直接转到 inflow.php 并将其传递的参数与页面传递的参数相同,我会得到一个看起来不错的 JSON 对象,但是当我查看 Chrome Developer's Tools 的响应时,我得到:
[]
仅此而已。
【问题讨论】:
-
看起来你的 $statment->fetch() 没有触发 while
-
你为什么使用
contentType: "application/json"?你正在发送一个 url 编码的文本字符串,所以你不应该使用它。 -
@Rooster 这是我最初的想法,然而,直接访问 php 页面会回显看起来像一个有效的 JSON 对象。