PHP receive json

与世无争的帅哥 提交于 2019-12-13 16:24:38

问题


I'm using knockout and this is my ajax code:

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

Using firebug I can see that the json message is sent correctly, the problem is how to receive it on PHP, what is the name of what has been sent?

I'm using CodeIgniter

Thanks in advance for any help.


回答1:


It would be in the variable $_POST['key'] where 'key' is the key values in the JSON object.




回答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;
    ?>



回答3:


  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) }
            });
        }

Use $_POST in the php file to get the data I am assumin you are using jquery as well and $ is the jquery function. Now this data is available in the post superglobal. NB: you need not use json to send data through the ajax function. Data is passsed in a serialized array format like: field1=value1&field2=value2 etc...

If you must however use json, which frankly is unnecessary, use data:"json="+ko.toJSON(form)

and on server side data=json_decode($_POST['json']);




回答4:


The solution is to take

contentType: "application/json",

from ajax call.

=)



来源:https://stackoverflow.com/questions/9280970/php-receive-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!