簡體   English   中英

無法使用php從jQuery AJAX中的json_encode獲取數據

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

我有一個從 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;
    }  

一個好的做法是始終捕獲錯誤。 在您的 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 像這樣在瀏覽器中點擊 url

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']);
    }

暫無
暫無

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

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