AJAX调用从json_encode返回空对象

时间:2014-11-12 17:50:17

标签: php ajax json pivot.js

我正在对一个相当简单的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的数组创建和echo:

<?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; 

&GT;

如果我直接转到inflow.php并传递参数与页面传递的相同,我会看到一个好看的JSON对象,但是当我看到响应Chrome Developer的工具时我得到了:

[]

仅此而已。

1 个答案:

答案 0 :(得分:1)

您正在发送表单数据,而不是json;

$.ajax({
        type:'POST',
        url:'inflow.php',
        data:$('#dates').serialize(),
        //contentType: "application/json",<-- remove this
        dataType: 'json',