鍍金池/ 問答/HTML/ ajax post 返回的數(shù)據(jù)是null

ajax post 返回的數(shù)據(jù)是null

因為form提交的時候頁面會自動提交到/apply 這個處理頁面,返回JSON數(shù)據(jù)
所以用ajax重定向到/applysuccess
重定向成功了可是數(shù)據(jù)怎么沒提交成功的樣子 獲取的時候看到都是null
求幫助

//ajax的代碼
 $.ajax({
        type: 'post',
        url: '/apply',
        async: true,
        dataType: 'json',
        data: $('#sub').serialize(),
        success: function (data) {

            $("#sub").attr("method", 'GET').attr("action", '/applysuccess');
            $('#apply').html('<h3>' + data.message + '</h3>');
            $('.count').html(' ' + data.count + ' ');
        }
    });

<!--這是表單的代碼-->
<form action="/apply" method="post" id="sub">

                <div class="form-group fl col-md-4">
                    <input class="form-control" name="first_name" placeholder="first name" required>
                    <input class="form-control" name="last_name" placeholder="last name" required>
                </div>
                <div class="form-group fl col-md-4">
                    <input class="form-control" name="position_id" placeholder="position id" required>
                    <input class="form-control" name="years_experience" placeholder="years experience" required>
                </div>
                <div class="form-group fl col-md-4">
                    <input class="form-control" name="expertise" placeholder="expertise" required>
                    <button id="applyBtn" type="submit" class="btn btn-primary btn-lg">Apply for Job NOW</button>
                </div>
            </form>
請輸入代碼
回答
編輯回答
小眼睛

更新:

<form id="form" ...>
    ...
    <input type="submit" value="提交"/>
</form>
<script>
    document.querySelector('#form').onsubmit = e => {
        // 你有修改 action 的做法,所以這里可能需要判斷一下現(xiàn)在 acion 的值然后做不同的操作
        const action = $('#suib').attr('action')
        if (action === '/apply') {
            $.ajax({
                type: 'post',
                url: '/apply',
                async: true,
                dataType: 'json',
                data: $('#sub').serialize(),
                success: function (data) {
                    $("#sub").attr("method", 'GET').attr("action", '/applysuccess');
                    $('#apply').html('<h3>' + data.message + '</h3>');
                    $('.count').html(' ' + data.count + ' ');
                }
            })
        } else if (action === '/applysuccess') {
            // TODO ...
        }

        // 阻止表單的默認(rèn)行為
        return false;
    }
</script>

ajax 里都沒傳要 post 的數(shù)據(jù)啊。

2017年3月8日 18:50