【问题标题】:Decoding json received from ajax in php file解码从php文件中的ajax接收的json
【发布时间】:2014-01-04 06:35:50
【问题描述】:

我通过 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 和 $_POST['json'] 有什么区别?

编辑: //开始

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

//结束 请给出明确的解释...

【问题讨论】:

    标签: jquery


    【解决方案1】:

    就像我给你一个提交 ajax 的例子一样。 form#data -> #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 post 获取数据的 php 文件。如果您有任何疑问或其他疑问,可以询问。

    【讨论】:

      【解决方案2】:

      您想转换或获取您在 php.ini 中编码的数组。 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>
      

      如果您有任何疑问,请告诉我。

      【讨论】:

      • 对不起,如果我没有清楚地提出我的查询。我需要访问 php 文件中的 json....我在我的 php 中回显只是为了检查输出...跨度>
      • @vivin 你可以使用 json_decode($_POST['json']) 为你的 php 并且可以使用数组
      • 我确实尝试过@Avi。但在我的警报中,它给出了一个包含 html 内容的巨大信息 -
      • @vivin 这是一种错误。请你告诉我确切的消息是什么警报。
      • 我发现警告消息... json_decode() 期望参数 1 是字符串,数组中给出... 我正在尝试使用 JSON.stringify。但即使是提交按钮的 preventDefault() 动作也没有执行。为什么会这样?
      【解决方案3】:

      如果您通过警报直接打印值,它将显示[Object],因为响应是 JSON 格式。试试alert(res[0].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
       }
      },
      
      猜你喜欢
      • 2018-01-23
      • 2013-05-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多