使用jQuery的$ .post()方法检索JSON表单数据时遇到问题 - javascript

我在使用jQuery的$ .post()方法从PHP文件检索JSON数据时遇到麻烦。

我可以看到在控制台中记录了XHR POST请求,但是没有出现响应消息。

有人可以说明为什么会这样吗?

形成

<form action="<?php echo htmlentities($_SERVER['SCRIPT_NAME']); ?>" method="post" id="gradeForm">
    <div class="form-group" id="currentGradeGroup">
        <label for="currentGrade">What is your current total grade?</label>
        <input type="text" class="form-control" name="currentGrade">
        <span class="help-block" id="currentGrade"></span>
    </div>
    <div class="form-group" id="targetGradeGroup">
        <label for="targetGrade">What is your target grade?</label>
        <input type="text" class="form-control" name="targetGrade">
        <span class="help-block" id="targetGrade"></span>
    </div>
    <div class="form-group" id="finalWorthGroup">
        <label for="finalWorth">What is your final exam worth?</label>
        <input type="text" class="form-control" name="finalWorth">
        <span class="help-block" id="finalWorth"></span>
    </div>
    <button type="submit" class="btn btn-primary">Submit</button>
</form>
<div id="ajax"></div>


**Server side code**

 <?php  


        $response = validate_form(); 

        if (!empty($response)) {

            echo '<pre>';
            var_dump($response);
            echo '</pre>';
            exit(json_encode($response));

        } else {

            $response = success();

            echo '<pre>';
            var_dump($response);
            echo '</pre>';
            exit(json_encode($response));

        }

        // validate form input

        function validate_form() {

            $response = array();

            // currentGrade must be filled out and be a number.

             if (! (filter_has_var(INPUT_POST, 'currentGrade') && (filter_input(INPUT_POST, 'currentGrade', FILTER_VALIDATE_INT)))) {

                $currentGrade = array();
                $currentGrade['msg'] = "You need to enter a number for current grade";
                $response[] = $currentGrade;
            }

            // currentGrade must be 0 or greater

            if ($_POST['currentGrade'] < 0) {

                $currentGrade = array();
                $currentGrade['msg'] = "Current grade must be greater than or equal to zero";
                $response[] = $currentGrade;

            } 

            // targetGrade must be filled out and be a number.

            if (! (filter_has_var(INPUT_POST, 'targetGrade') && (filter_input(INPUT_POST, 'targetGrade', FILTER_VALIDATE_INT)))) {

                $targetGrade = array();
                $targetGrade['msg'] = "You need to enter a number for target grade";
                $response[] = $targetGrade;
            }

            // finalWorth must be filled out and be a number.

            if (! (filter_has_var(INPUT_POST, 'finalWorth') && (filter_input(INPUT_POST, 'finalWorth', FILTER_VALIDATE_INT)))) {

                $finalWorth = array();
                $finalWorth['msg'] = "Your final exam worth needs to be a number.";
                $response[] = $finalWorth;
            }

            $response['success'] = false;
            return $response;

        }

        function success() {

                $response = array();

                $currentGrade = $_POST['currentGrade'];
                $targetGrade = $_POST['targetGrade'];
                $finalWorth = $_POST['finalWorth'];

                $possibleGradeSoFar = (100 - $finalWorth) / 100;
                $finalWorth = $finalWorth / 100;
                $b = $currentGrade * $possibleGradeSoFar;
                $c = $targetGrade - $b;
                $neededMark = $c / $finalWorth;
                $neededMark = round($neededMark);

                $response['msg'] = '<p id="response">You need to get ' . $neededMark . ' to get a final mark of ' . $targetGrade . '.</p><br>';

                if ($neededMark >= 50 && $neededMark <= 100) {
                    $response['header'] = '<h1>Better start studying...</h1><img class="img-responsive" src="img/Mike.gif" alt="Mike">';
                } elseif ($neededMark > 100) {
                    $response['header'] = '<h1>Just give up now.</h1><img class="img-responsive" src="img/Gustavo-fring.gif" alt="Gustavo Fring">';
                } elseif ($neededMark < 50) {
                    $response['header'] = '<h1>Time to party!</h1><img class="img-responsive" src="img/Yeah-science.gif" alt="Yeah Science!">';
                }

                $response['success'] = true;
                return $response;

        }

从单独的PHP文件中的json_encode()输出的JSON

{
    "0": {
        "msg": "You need to enter a number for current grade"
    },
    "1": {
        "msg": "You need to enter a number for target grade"
    },
    "2": {
        "msg": "Your final exam worth needs to be a number."
    },
    "success": false
}

jQuery的

jQuery(document).ready(function($) {
    $('#gradeForm').submit(function(e) {
        // stop form from submitting normally.
        e.preventDefault(); 

        // get some values from the form.
        var $form = $(this);
        var url = $form.attr('action');
        var postData = $form.serialize();

        // use the jQuery post method to send the data.
        var posting = $.post(url, postData, 'json'); 

        // If the request is successful append the response to the #ajax div.
        posting.done(function(response) {
            // output the appropriate message in the ajax div 
            $('#ajax').html(response[0].msg);
        }) // end done();
        // otherwise log the HTTP request status to the console.
        .fail(function(jqXHR) {
            console.log(jqXHR.status);
            console.log(jqXHR.statusText);
        }); // end fail();
    }); // end submit();
}); // end ready();

参考方案

响应为:

{
    "0": {
        "msg": "You need to enter a number for current grade"
    },
    "1": {
        "msg": "You need to enter a number for target grade"
    },
    "2": {
        "msg": "Your final exam worth needs to be a number."
    },
    "success": false
}

尝试response.0.msg或这样:

$.post(url, postData,function(data)
{
  alert(data.0.msg);
}, 
'json'); 

或者,您可以将响应更改为:

$response = (array("results" => $result_array_with_msg, "success" => $success));

如何在没有for循环的情况下在Javascript中使用Django模板标签 - javascript

我想在JavaScript中使用模板变量:我的问题是在javascript代码中使用for循环,for循环之间的所有事情都会重复..但我不想要....下面粘贴了我的代码..有人可以告诉我更好的方法吗这..因为这看起来很丑..这是我的代码: {% block extra_javascript %} <script src="/static/js…

为什么我的jquery / ajax帖子未在我的php代码中注册? - javascript

因此,我尝试使用PHP和AJAX构建一个单页应用程序,但导航遇到一些问题。我有一个文件controller.php控制要显示的页面。处理发布请求的代码如下编辑:忘记提及回显$_POST['page']什么也没显示if(!isset($_POST['page'])){ include('Pages/landin…

打印二维阵列 - javascript

我正在尝试打印子元素。在this example之后。怎么做?。$myarray = array("DO"=>array('IDEAS','BRANDS','CREATIVE','CAMPAIGNS'), "JOCKEY"=>a…

使用JS和PHP更改弹出窗口背景图像 - javascript

我有一个JS函数:function zoom(now) { document.getElementById("popup").style.display = "block"; document.getElementById("photos").style.backgroundImage = …

变更事件时道具无法正常工作 - javascript

我有一些代码,当用户从下拉列表中选择一个项目时,这会触发一个change事件,然后调用php页面进行处理。首次加载页面时,我选择一个项目,并在触发change事件时,这应更改所选select输入的占位符并禁用相同的输入:“#box_ffrtv”。但是,发生的事情是更改仅在我在下拉菜单中进行了第二选择之后才发生,然后更改了占位符并禁用了输入。我对jquery还…