2012-02-14 55 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; 
    ?>