使用php无法从jQuery AJAX中的json_encode获取数据

时间:2017-01-08 14:36:26

标签: php jquery ajax

我有一个从jQuery到PHP的AJAX调用,其中PHP使用json_encode数组进行响应,但是在jQuery中无法访问数组的值。
状态正常,但responseText为undefined

$(document).ready(function () {
    $("#comments_form").on("submit", function(e) {
        e.preventDefault();
        e.stopPropagation();

        $.ajax({
            type: 'POST',
            url: 'process_in.php',
            data: {
                first: $("#firstname").val(), 
                second: $("#lastname").val(), 
                third: $("#mail").val(), 
                fourth: $("#phone").val(), 
                fifth: $("#message").val()
            },
            success: function(result) {                    
                var x = jQuery.parseJSON(result);
                alert(x.f);
            },
        });
    });  
})
<?php
    include ('connection.php');
    if (isset($_REQUEST['first']) && isset($_REQUEST['second']) &&   isset($_REQUEST['third']) && isset($_REQUEST['fourth']) && isset($_REQUEST['fifth'])) 
    {
        $firstname = $_REQUEST['first'];
        $lastname = $_REQUEST['second'];
        $email = $_REQUEST['third'];
        $contact = $_REQUEST['fourth'];
        $message = $_REQUEST['fifth'];

        $data = array();
        $data["f"] = xssafe($firstname);
        $data["l"] = xssafe($lastname);
        $data["e"] = xssafe($email);
        $data["c"] = xssafe($contact);
        $data["m"] = xssafe($message);
        echo json_encode($data);
    }

    function xssafe($d)
    {
        $x = filter_var($d, FILTER_SANITIZE_STRING);
        return $x;
    }  

1 个答案:

答案 0 :(得分:0)

一个好的做法是始终抓住错误。在您的ajax请求中,没有错误回调来处理异常。  使用dataType: "JSON"代替jQuery.parseJSON();,这样如果json处于不可解析状态,您将在错误块中获得回调。

$.ajax({
    type: 'POST',
    url: 'process_in.php',
    dataType: 'JSON',
    data: {
        first: $("#firstname").val(), 
        second: $("#lastname").val(), 
        third: $("#mail").val(), 
        fourth: $("#phone").val(), 
        fifth: $("#message").val()
    },
    success: function(result) {                    
        console.log(result.f);
    },
    error: function (jqXHR, exception) {
        var msg = '';
        if (jqXHR.status === 0) {
            msg = 'Not connect.\n Verify Network.';
        } else if (jqXHR.status == 404) {
            msg = 'Requested page not found. [404]';
        } else if (jqXHR.status == 500) {
            msg = 'Internal Server Error [500].';
        } else if (exception === 'parsererror') {
            msg = 'Requested JSON parse failed.';
        } else if (exception === 'timeout') {
            msg = 'Time out error.';
        } else if (exception === 'abort') {
            msg = 'Ajax request aborted.';
        } else {
            msg = 'Uncaught Error.\n' + jqXHR.responseText;
        }
        console.log(msg);
    }
});

您可以学习如何调试代码并检查错误日志

现在让我们来看看你的代码,有很多可能的情况你没有获得价值。

它可能是你的php代码,也可能是你的jquery。

在php中检查它返回一个有效的json是否在这个浏览器中点击了这个

http://.../process_in.php?first=foo&second=foo&third=foo&fourth=foo&fifth=foo

在您的PHP代码中,您没有返回任何值,因此为

添加其他部分
    if (isset($_REQUEST['first']) && isset($_REQUEST['second']) &&   isset($_REQUEST['third']) && isset($_REQUEST['fourth']) && isset($_REQUEST['fifth'])) 
    {
        $firstname = $_REQUEST['first'];
        $lastname = $_REQUEST['second'];
        $email = $_REQUEST['third'];
        $contact = $_REQUEST['fourth'];
        $message = $_REQUEST['fifth'];

        $data = array();
        $data["f"] = xssafe($firstname);
        $data["l"] = xssafe($lastname);
        $data["e"] = xssafe($email);
        $data["c"] = xssafe($contact);
        $data["m"] = xssafe($message);
        echo json_encode($data);
    } else {
        echo json_encode(['error'=>'Invalid request']);
    }