如何在ajax请求中传递json数据

时间:2019-02-08 15:03:57

标签: json

以下代码可以正常工作:

$ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, 'api.hackerrank.com/checker/submission.json');
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($ch, CURLOPT_POSTFIELDS, 'source='.$sourceCode.'&lang=2&testcases=["1"]&api_key=hackerrank|1012942-759|ad05befda57bc43f1358ebee988682e4cc7ecd02');

  curl_setopt($ch, CURLOPT_POST, 1);

  $headers = array();
  $headers[] = 'Content-Type: application/x-www-form-urlencoded';
  curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

  $result = curl_exec($ch);
  if (curl_errno($ch)) {
    echo curl_error($ch);
  }
  curl_close ($ch);

  echo $result;

现在我将ajax请求中的测试用例值设置为以下更改:

 $testCases = $_POST['testcases'];
  curl_setopt($ch, CURLOPT_POSTFIELDS, 'source='.$sourceCode.'&lang=2&testcases='.$testCases.'&api_key=hackerrank|1012942-759|ad05befda57bc43f1358ebee988682e4cc7ecd02');

ajax请求是:

<?php   $input = array("1");
                $input = json_encode($input);
        ?>
        $('#submitCode').on('click', function(evnt){
              evnt.preventDefault();

          var souceCode = encodeURIComponent(cEditor.getValue());
              var button = $(this),
                  ajax_url = '<?php echo admin_url("admin-ajax.php"); ?>',
                  data = {
                      action: 'get_output_by_ajax',
                      sourceCode : souceCode,
                      lang: 2,
                                    post_id: '<?php echo $post_id; ?>',
                      testcases: <?php echo $input; ?>,
                      security: '<?php echo wp_create_nonce("get_output"); ?>'
                  };

              $.post(ajax_url, data, function (response) {
                        obj = JSON.parse(response);
                         console.log(response); 
              }).always(function () {
                  $('.result-processing').addClass('hide');
              });

            });

对于此修改,我收到以下错误:

{"result":{"errors":{"testcases":"Testcases should be a valid json."}}}

但是testcases=["1"]testcases='.$testCases应该完全相同。我的代码有什么问题?

1 个答案:

答案 0 :(得分:0)

您必须引号array("/"1/""),以使“成为字符串的一部分。