簡體   English   中英

帶有JSON對象解析的jQuery ajax GET方法

[英]Jquery ajax GET method with an object parse in JSON

感謝您對這種錯誤的行為發表意見:

此代碼的工作方式:

JS代碼:

$.ajax({ 
        url: "ajouterEntreeParExcel.ajax.php", // url de la page à charger
        data: {"name":"John","date":"05 & 06 mars"},
        cache: false, // pas de mise en cache
        async: false, 
        contentType : "application/json",
        dataType: "json",
        success:function(jsonRetour){

        },
        error:function(XMLHttpRequest, textStatus, errorThrows){ // erreur durant la requete

        }
    });

和PHP代碼:

        $name = $_GET["nom"];
        $date = $_GET["date"];

而且這不起作用

    var dataAjax = {};
    dataAjax["name"] = "John";
    dataAjax["date"] = "05 & 06 mars";
    var entree = JSON.stringify(dataAjax);

    $.ajax({ 
        url: "ajouterEntreeParExcel.ajax.php", // url de la page à charger
        data: entree,
        cache: false, // pas de mise en cache
        async: false, 
        contentType : "application/json",
        dataType: "json",
        success:function(jsonRetour){

        },
        error:function(XMLHttpRequest, textStatus, errorThrows){ // erreur durant la requete

        }
    });

用相同的PHP代碼。 在使用firebug進行調試中,我檢查了變量“ entree”,它的格式正確,但是在PHP方面我什么也沒得到。

注意:我更喜歡使用GET類型而不是POST類型。

任何想法 ?

這是因為在第一個請求中,您以x-www-form-urlencoded發送數據,這就是您的PHP代碼所期望的:

name=John&date=05 & 06 mars

在第二個請求中,您將在請求中發送JSON格式的數據,例如:

'{"name":"John","date":"05 & 06 mars"}'

還要注意,您應該刪除async: false因為使用它被認為是可怕的做法。 如果您檢查控制台,則會看到瀏覽器有關其使用的警告。

因此,為了使版本可以處理對象並提供給定的響應對象,此代碼可以工作:

    var dataAjax = {};
    dataAjax["date"] = obj["Date"];
    dataAjax["comite"] = obj["Comité Int.Rég."];


    $.ajax({ 
        url: "ajouterEntreeParExcel.ajax.php", // url de la page à charger
        data: dataAjax,
        cache: false, // pas de mise en cache
        //async: false, 
        //contentType : "application/json",
        dataType: "json",
        success:function(jsonRetour){
            printValueTraitee = printValueTraitee + '<span class="green">OK</span>';
        },
        error:function(XMLHttpRequest, textStatus, errorThrows){ // erreur durant la requete
            printValueTraitee = printValueTraitee + '<span class="red">KO</span>';
        }
    });

因此,我不再發送JSON格式的數據,而只是像不帶字符串的對象一樣。

暫無
暫無

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

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