代码之家  ›  专栏  ›  技术社区  ›  Abdus Sattar Bhuiyan

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

  •  0
  • Abdus Sattar Bhuiyan  · 技术社区  · 6 年前

    以下代码工作正常:

    $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值设置为以下更改:

     $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 回复  |  直到 6 年前
        1
  •  0
  •   nologin    6 年前

    你必须引用 array("/"1/"") 所以“变成了字符串的一部分。