JSON.stringify回来了吗?

时间:2013-07-02 13:33:55

标签: javascript jquery json

我正在尝试json序列化数组,如下所示:

function postToDrupal(contacts, source, owner) {
  (function ($) {

    var contact, name, email, entry;
    var emails = [];
    var post_object = {};    

    for (var i = 0; i < contacts.length; i++) {
      contact = contacts[i];
      emails[i] = {};
      emails[i]['name'] = contact.fullName();
      emails[i]['email'] = contact.selectedEmail();
      console.log(contacts.length)
    }

    post_object['emails']=emails;
    post_object['source']=source;
    post_object['owner']=owner;

    $.post("/cloudsponge-post",JSON.stringify(post_object),function(data) {

    window.location.href = "/after-import";

    });
  }(jQuery));
}

问题是,帖子回来了。如果没有JSON.stringify(),我会获得所有元素(但是有数千个元素可以达到某些服务器限制,因此需要序列化)。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:2)

问题是这样的。当对服务器的请求是JSON类型时,它不是严格意义上的POST,因此PHP不会填充$ _POST字段。为了检索数据,必须直接从请求中读取数据,换句话说,不要使用$ _POST,而是使用:

$data=file_get_contents("php://input");

答案 1 :(得分:1)

您无需致电JSON.stringify,$ .post接受一个对象,请检查$.post

一次发布几封电子邮件的代码:

function postToDrupal(contacts, source, owner) {
    var pending = 0, limit = 10;
    var post_patch = function(emails) {
        var post_object = {};
        post_object['emails']=emails;
        post_object['source']=source;
        post_object['owner']=owner;
        pending++;
        $.post("/cloudsponge-post", post_object,function(data) {
            if(pending-- == 0) {
                window.location.href = "/after-import";
            }
        });
    }
    (function ($) {

        var contact, emails = [];   

        for (var i = 0; i < contacts.length; i++) {
            contact = contacts[i];
            emails[i] = {};
            emails[i]['name'] = contact.fullName();
            emails[i]['email'] = contact.selectedEmail();
            console.log(contacts.length)
            if(limit-- == 0) {
                limit = 10
                post_patch(emails);
                contact = null; emails = {};
            }
        }

    }(jQuery));
}