如何使用jquery POST并捕获JSON格式的回复


How to POST using jquery and capture the reply in JSON

我正在使用这个代码:

function save() {
    // submit the dataform
    $.post(document.dataform.action, 
        $("#dataform").serialize(),
        function(reply) {
           //handle reply here
    });
}

将正确的数据发送到服务器,但它到达$_GET。当我修改服务器代码以匹配时,我得到了预期的回复。action上有一部分查询。

我如何才能真正得到POST发送数据从表单,使它到达$_POST,从而避免对get的大小限制?

我正在测试Firefox, JQuery 9和PHP 5.4.3

谢谢,伊恩。

$_GET从查询字符串中获取参数,所以要有$_POST和$_GET,只需这样做:

var action       = document.dataform.action;
var get_variable = "var1=v1&var2=v2..."; 
action = action+"?"+get_variable;
$.post(action, 
        $("#dataform").serialize(),
        function(reply) {
           //handle reply here
    });
function save() {
    // submit the dataform
    $.post(document.dataform.action, 
        { data: $("#dataform").serializeArray() })
    .done(function(reply) {
           //handle reply here
    });
}

然后json_decode ($ _POST['数据']);在PHP中

成功了!正确的方法是

function save() {
    // submit the dataform
    $.ajax({
    url: document.dataform.action,
    data: new FormData(document.dataform),
    cache: false,
    contentType: false,
    processData: false,
    type: 'POST',
    success: function(reply){
        if (reply.action) fetch('/content.php',reply.action);
        if (reply.content) document.getElementById('content').innerHTML=reply.content;
        if (reply.menu) document.getElementById('menu').innerHTML=reply.menu;
        if (reply.status) document.getElementById('status').innerHTML=reply.status;
        calcSize();
        }
    });
}

然而,这只适用于支持FormData的浏览器- Chrome 7+, FF4.0+, IE 10+, Opera 12+和Safari 5+
对于我的用例来说是OK的;)谢谢大家的意见。