解码json从php文件中的ajax接收

时间:2014-01-04 06:35:50

标签: jquery

我通过ajax调用将json对象传递给我的php文件。

jQuery语法

$.getJSON('http:..Sample/JsonCreation.php', function(data)
{
   //data has the json - I am trying to edit this json and then pass it to another php file through ajax and save in DB. I have successfully edited but unable to access the passed json in my php file.
   questionsArray = data;
}
$('form').on('submit', function(event)
{
//AJAX CALL
                $.ajax
                ({
                    url: "updateTestReport.php",
                    type: "post",
                    //JSON.stringify
                    data: {json:(questionsArray)},
                    contenttype: "application/json; charset=utf-8",
                    datatype: "text",

                    success: function(data)
                    {
                        //alert("success");
                        alert(data);
                    },
                    error:function()
                    {
                        alert("failure");
                    }
                });
});

PHP文件

<?php

//$contentjson = file_get_contents("php://input");
//echo $_POST['json'];
$questionsArray = json_encode($_POST['json']);
echo $questionsArray;


?>

输出:

[{"questionNumber":"1","quesDesc":"The price of petrol has increased by 25%.By what percentage should it now be reduced to return to the original price?","optionA":"25%","optionB":"20%","optionC":"15%","optionD":null,"correctOption":"A","selectedAnswer":null,"isQuestionViewed":null},{"questionNumber":"2","quesDesc":"Price of cooking gas has increased by 10%. By what percentage should consumption be reduced to keep expenditure unchanged?","optionA":"9.09%","optionB":"10%","optionC":"11.11%","optionD":null,"correctOption":"A","selectedAnswer":null,"isQuestionViewed":null},{"questionNumber":"3","quesDesc":"A buys a shirt for Rs 100 and sells it to B for Rs 120. B now sells it to C for Rs 144. Had A sold it directly to C at the price C paid for it, then his profit % would have been","optionA":"10%","optionB":"20%","optionC":"44%","optionD":null,"correctOption":"C","selectedAnswer":null,"isQuestionViewed":null}]

1)php文件中的json_encode如何给出输出。我不应该使用json_decode吗? 2)即使通过编码的json,我也无法检索值。请让我知道如何从这个json访问值... 3)file_get_contents&amp;的区别是什么? $ _POST [ 'JSON']?

编辑: //开始

我需要在php文件中访问我的json,检索一些值,进行一些计算,保存在DB中。然后返回主html文件。

// END 请明确解释......

3 个答案:

答案 0 :(得分:0)

如果您通过警告直接打印值,它将显示[Object],因为响应是JSON格式。试试alert(res[0].questionNumber),这会显示第一个questionNumber

尝试这样的方法来访问值

success: function(res)
{
 for(var i=0;i<res.length;i++)
 {
    qno = res[i].questionNumber;
    desc = res[i].quesDesc;
    // and so on
    // do whatever you want this data
 }
},

答案 1 :(得分:0)

您想要转换或获取您在php中编码的数组。我已经为你提供了ajax的解决方案

<script>
            $.ajax
                    ({
                        url: "updateTestReport.php",
                        type: "post",
                        //JSON.stringify
                        data: {json: (questionsArray)},
                        contenttype: "application/json; charset=utf-8",
                        datatype: "text",
                        success: function(data)
                        {
                            /*
                             * Below this comment you can also use 
                             * data = jQuery.parseJSON(data);
                             * It will decode json encoded
                             */
                            data = jQuery.parseJSON(data);
                            alert(data.questionNumber);
                            alert(data.quesDesc);
                            /*
                             * put the array keys using the period in between with data variable
                             * 
                             */
                            alert(data);
                        },
                        error: function()
                        {
                            alert("failure");
                        }
                    });
        </script>

如果您有任何疑问,请与我们联系。

答案 2 :(得分:0)

就像我给你一个提交ajax的例子。 表格#data - &gt; #data是表单的id

<script>
    $("form#data").submit(function() {
        if($("form#data").validationEngine('validate') != true){
         return false;
         }
        var formData = new FormData($(this)[0]);

        $.ajax({
            url: '/test/test.php',
            type: 'POST',
            data: formData,
            async: false,
            success: function(data) {
                data = jQuery.parseJSON(data);
                if (data.result == true) {
                    alert('Your details updated successfully.');
                }
                else if (data.result == false) {
                    alert("Your details not updated!");
                }
            },
            cache: false,
            contentType: false,
            processData: false
        });

        return false;
    });
</script>

现在我向您展示ajax调用请求的test.php。

<?php
if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && ( $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest' )) {
    $mt = $_POST['tmt'];
    if($mt!=NULL){
            $res11['result']=TRUE;
        }else{
            $res11['result']=FALSE;
        }
        echo json_encode($res11);
}
?>

这是通过ajax帖子获取数据的php文件。如果您有任何疑问或其他疑问,可以询问。