1

我正在尝试按如下方式对数组进行 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() 我得到了所有的元素(但是有成千上万的元素,这可能会达到某些服务器的限制,因此需要对它们进行序列化)。任何帮助将非常感激。

4

2 回答 2

2

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

$data=file_get_contents("php://input");
于 2013-07-02T14:21:29.990 回答
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));
}
于 2013-07-02T13:37:14.687 回答