2012-01-30 53 views
1

我有以下

var storage = [], obj; 
    $('form input[type=hidden]').each(function(){ 
     obj = {}; 
     obj[this.name] = this.value; 
     obj["spot"] = this.className 
     storage.push(obj); 
    }); 

    storage = $.toJSON(storage); 
    console.log(storage); 

    $.post('storage/', storage, function(data) { 
     if(data == "true") { 
      //window.location.href = href; 
     }else{ 
      alert("An error has been encountered, Blah has been notified, please try again later"); 
     } 
    }); 

和PHP我有一个简单<?php print_r($_POST); ?>,它是印刷Array()它似乎并没有被张贴JSON编码的结果。

这使我疯狂,我不知道发生了什么事大声笑。任何帮助?

ps。我使用http://code.google.com/p/jquery-json/作为json编码器。

+0

你从'console.log()'中得到了什么? – Treffynnon 2012-01-30 19:39:44

回答

2

jQuery的ajax数据选项需要一个对象或查询字符串。你传递的是一个json字符串,它并不期待。试试这个来代替:

$.post('storage/', {storage: storage}, function(data){...}); 

,并在PHP中,与$_POST["storage"]

编辑访问值:另外,data == "true"/true/i.test(data)只是在情况下你的PHP返回任何隐藏字符,如空格选项卡或退货。

+1

他也可以使用$ json = json_decode(file_get_contents(“php:// input”));将发布的json转换为可用的变量,而不使用POST变量 – Rahly 2012-01-30 19:47:49

+0

的确如此。这有什么不利吗? jquery如何知道将它作为请求体而不是post/get var发送?我在文档中找不到任何关于它的信息,这就是为什么我远离它。 – 2012-01-30 19:58:56

+0

它只会成为原始的请求主体,这是非常有效的,并且在您希望提供简单服务的跨语言简单方法(任何语言/方言只是将json写入您的应用)时非常有用。在这种情况下,建议设置一个“Content-Type”标题。 – Wrikken 2012-01-30 20:51:27