【问题标题】:Jquery ajax GET method with an object parse in JSONJquery ajax GET 方法与 JSON 中的对象解析
【发布时间】:2017-03-20 01:44:39
【问题描述】:

感谢您说出您对这种神秘行为的看法:

此代码有效:

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 代码。 在 Debug with firebug 中,我检查了变量“entre”,它的格式很好,但我在 PHP 端没有得到任何东西。

注意:我更喜欢使用 GET 类型而不是 POST 类型。

有什么想法吗?

【问题讨论】:

  • 永远不要使用async: false!这是一种糟糕的做法,现在已被弃用

标签: php jquery ajax get stringify


【解决方案1】:

这是因为在第一个请求中,您将数据发送为x-www-form-urlencoded,这是您的 PHP 代码所期望的:

name=John&date=05 & 06 mars

而在第二个中,您在请求中发送 JSON 格式的数据,例如:

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

还请注意,您应该删除async: false,因为使用它被认为是一种可怕的做法。如果你检查你的控制台,你会看到一个关于它的使用的浏览器警告。

【讨论】:

  • 但是第一个命题中的 {"name":"John","date":"05 & 06 mars"} 翻译成 name=John&date=05 & 06 mars 吗?是否有可能对“动态”版本进行相同的翻译,我想将对象作为字符串发送?
  • 由jQuery内部翻译。如果需要,您可以将字符串作为 JSON 发送,但您需要修改 PHP 代码以正确读取它。就我个人而言,我不会打扰,因为默认情况下 PHP 已设置为可以正常工作。您在第一个示例中使用的代码没有任何问题。
【解决方案2】:

因此,为了使版本与对象和给定的响应一起工作,此代码可以工作:

    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 格式发送我的数据,而是像一个没有字符串化的对象一样。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-03
    • 2014-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多