簡體   English   中英

ajax 在 chrome 上工作但不能在 firefox 和 safari 上工作

[英]ajax post working on chrome but not working on firefox and safari

I've encountered an issue where a jquery ajax post method works on chrome but does not work on safari or firefox. 我瀏覽了所有其他類似的帖子,但它們並沒有解決問題。 每當我運行 ajax 代碼時,它只會返回表單所在頁面的整個 HTML。

這是我的 javascript:

 $("#piece-form").submit(function(e) { e.preventDefault(); // gets which submit button was clicked var selectedButton = $(this).find("input[type=submit]:focus"); var url = selectedButton.attr("name"); var formData = new FormData(this); $.ajax ( { type: "POST", url: url, data: formData, cache: false, processData: false, success: function(data) { if(data == "Success.") { $("#error-box"),css("display"; "none"). $("#success-box").html("Success. Publishing.;."), $("#success-box");css("display". "block"), } else { $("#success-box");css("display". "none"); $("#error-box").html(data), $("#error-box");css("display"; "block"); } } } ) });

無論 function 指向的 PHP 文件的內容如何,它都無法按計划工作。 我試過用一條回顯線制作一個 PHP 文件,但我仍然遇到同樣的問題。 我也在 ajax 中實現了一個錯誤塊,它什么也不返回。 我也沒有在控制台中收到錯誤消息,除了:“主線程上的同步 XMLHttpRequest 已被棄用,因為它對最終用戶的體驗有不利影響。更多幫助http://xhr.spec.whatwg.org/”在 Firefox

編輯:我添加了 contentType:false 並且它在 Firefox 和 Safari 上仍然無法正常運行

您是否嘗試將代碼包裝在准備好的文檔中?
據我所知,使用 on() 是正確的:

$( document ).ready(function() {
    $("#piece-form").on('submit', function(e){
        //your main code here
    });
});

目前看來不會有任何問題。 ..

我終於找到了答案。

錯誤在以下代碼行中:

 var selectedButton = $(this).find("input[type=submit]:focus"); var url = selectedButton.attr("name");

由於某種原因,Firefox 和 Safari 無法正確獲取“selectedButton”的值(盡管 Chrome 可以)導致 url 變量設置不正確。 為了避免這種情況,我做了以下事情:

 $(".piece-button").click(function (){
    url = $(this).attr("name");
})

我需要 submitButton 方法,因為我有兩個用於表單的提交按鈕,並且試圖找到點擊了哪個按鈕。 這種替代方法可以做到這一點,並且可以在我測試過的所有三個瀏覽器中轉移。 這可能不是兩個按鈕提交問題的最佳解決方案,但它對我有用,現在 ajax 工作順利。

盡管您已經找到了解決方案,但出於興趣,我正在分享我的解決方案,因為我剛剛遇到了同樣的問題並通過添加event.preventDefault(); success后。 給出了示例代碼

$(document).ready(function() {

    $('form').on('submit', function(event) {

        $.ajax({
                data: {
                    name: $('#nameInput').val(),
                    email: $('#emailInput').val()
                },
                type: 'POST',
                url: '/post_for_db',
                success: function(data) {
                    console.log(data)
                    $("body").html(data);
                    // This will navigate to your preferred location
                    document.location = '/render_table_from_db';
                },
        event.preventDefault(); // solution is this for me
    });
});

暫無
暫無

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

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