簡體   English   中英

AJAX調用從json_encode返回空對象

[英]AJAX call returning empty object from json_encode

我正在對一個相當簡單的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開發者工具:

[]

僅此而已。

您正在發送表單數據,而不是json;

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM