简体   繁体   English

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

[英]Cannot get data from json_encode in jQuery AJAX with php

I have an AJAX call from jQuery to PHP where the PHP responds with a json_encode array, but the values of the array are not accessible in jQuery.我有一个从 jQuery 到 PHP 的 AJAX 调用,其中 PHP 使用json_encode数组进行响应,但在 jQuery 中无法访问该数组的值。
The status is OK, but the responseText is undefined .状态正常,但 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;
    }  

A good practice is to always catch the errors too.一个好的做法是始终捕获错误。 In your ajax request there is no error callback to handle the exception.在您的 ajax 请求中,没有处理异常的错误回调。 Use dataType: "JSON" instead of jQuery.parseJSON();使用dataType: "JSON"而不是jQuery.parseJSON(); so that if json in unparsable you get the callback in the error block.这样如果 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);
    }
});

You can learn how to debug the code and check your error logs您可以学习如何调试代码并检查错误日志

Now lets get to your code, there are many possible cases that you are not getting the value.现在让我们来看看你的代码,有很多可能的情况你没有得到值。

It could be your php code or it could be your jquery.它可能是您的 php 代码,也可能是您的 jquery。

In php to check whether its returning a valid json hit the url in browser like this在 php 中检查它是否返回一个有效的 json 像这样在浏览器中点击 url

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

As in your php code you haven't return any value so add an else part for the就像在您的 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']);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM