2012-02-14 52 views
1

我使用的是淘汰赛,这是我的Ajax代码:PHP收到JSON

save: function() { 
       $.ajax({ 
        url:"http://localhost/loyalty/welcome/json/", 
        type: "post", 
        data: ko.toJSON(this), 
        contentType: "application/json", 
        success: function (result) { alert(result) } 
       }); 
      } 

使用Firebug我可以看到JSON消息被正确发送,则问题是如何得到它PHP是什么已发送的内容的名称?

我正在使用CodeIgniter

在此先感谢您的帮助。

回答

0

解决的办法是采取

contentType: "application/json", 

从AJAX调用。

=)

2

它将在变量$_POST['key']其中'key'是JSON对象中的键值。

+0

嗨,你好,我收到这个JSON:[{ “Name”: “JOA£O”, “isOnTwitter”:假}],并使用$ _ POST [ '名']没有返回。 – Gerep 2012-02-14 17:07:06

+1

您的JSON位于数组中。你只需要在周围有'{}'的一个裸物体。否则它是一个数组,你需要给它一个名字。类似于“{”jsonval“:ko.toJSON(this)}' – Ktash 2012-02-14 17:08:50

+0

表单数据不会使用json传递。 HTTP有自己的格式来传输数据。使用form.serialize() – 2012-02-14 17:10:26

0
save: function() { 
      $.ajax({ 
       url:"http://localhost/loyalty/welcome/json/", 
       type: "post", 
       data: $(this).serialize()/*Where this is an instance of the form change with appropriate selector such as #loginForm*/, 
       contentType: "application/json", 
       success: function (result) { alert(result) } 
      }); 
     } 

使用$ _ POST在PHP文件来获取数据 我assumin你正在使用jQuery,以及和$是jQuery的功能。现在这个数据可以在超全球职位中找到。注意:您不需要使用json通过ajax函数发送数据。数据以串行化数组格式传递,如:field1 = value1 & field2 = value2 etc ...

如果您必须使用json,这是坦率地说是不必要的,请使用data:“json =”+ ko.toJSON )

并在服务器端data = json_decode($ _ POST ['json']);

2
**This is what exactly the way to post as json way** 

//index.php 
    $(document).ready(function(){ 
       obj = {} 
       obj.name = "sam" 
       obj.value = "12345" 
         $.ajax({ 
           url:"json.php", 
           type: "post", 
           data :obj, 
           dataType:"json", 
           success: function (result) { 
            alert(result.name); 
           } 
          }); 
      }); 

    //json.php ,, the posted data is received as array ,, so we need to convert it as //json_encode to make as JSON again 

    <?php 
    $jsonReceiveData = json_encode($_POST); 
    echo $jsonReceiveData; 
    ?>