programing

jquery ajax와 함께 JSON을 PHP에 게시하는 중

starjava 2023. 10. 14. 09:26
반응형

jquery ajax와 함께 JSON을 PHP에 게시하는 중

json 문자열을 해독하고 ajax로 통과한 후 결과를 스탬프로 찍는 간단한 php 파일이 있지만 유지할 수 없습니다.$_POST변수, 왜

fireBug로 검사를 해보니 POST 요청이 올바르게 전송되고, php 스크립트가 호출되면 Noooob에 응답하고, POST 변수가 설정되어 있는 것 같습니다.

제가 원하는 것은 제 어레이를 갖는 것입니다 =)

생성된 JSON 문자열JSON.stringify:

[
   {
      "id":21,
      "children":[
         {
            "id":196
         },
         {
            "id":195
         },
         {
            "id":49
         },
         {
            "id":194
         }
      ]
   },
   {
      "id":29,
      "children":[
         {
            "id":184
         },
         {
            "id":152
         }
      ]
   },
   ...
]

자바스크립트

$('#save').click(function() {
  var tmp = JSON.stringify($('.dd').nestable('serialize'));
  // tmp value: [{"id":21,"children":[{"id":196},{"id":195},{"id":49},{"id":194}]},{"id":29,"children":[{"id":184},{"id":152}]},...]
  $.ajax({
    type: 'POST',
    url: 'save_categories.php',
    dataType: 'json',
    data: {'categories': tmp},
    success: function(msg) {
      alert(msg);
    }
  });
});

save_categories.php

<?php
  if(isset($_POST['categories'])) {
    $json = $_POST['categories'];
    var_dump(json_decode($json, true));
  } else {
    echo "Noooooooob";
  }
?>

제거하면 코드가 작동합니다.dataType: 'json', 방금 시험해 봤어요.

$('#save').click(function() {
  var tmp = JSON.stringify($('.dd').nestable('serialize'));
  // tmp value: [{"id":21,"children":[{"id":196},{"id":195},{"id":49},{"id":194}]},{"id":29,"children":[{"id":184},{"id":152}]},...]
  $.ajax({
    type: 'POST',
    url: 'save_categories.php',
    data: {'categories': tmp},
    success: function(msg) {
      alert(msg);
    }
  });
});

제가 할 수 있는 일인데 이걸 시도해 보세요.자바스크립트

$('#save').click(function() { $.ajax({ type: 'POST', contentType: 'application/json', url: 'save_categories.php', dataType: 'json', data: JSON.stringify({'categories': $('.dd').nestable('serialize')}), success: function(msg) { alert(msg); } }); });

save_categories에 아래 코드를 작성해야 합니다.php $_POST는 양식 데이터로 미리 채워집니다.

JSON 데이터(또는 원시 입력)를 가져오려면 php://input을 사용합니다.

$json = json_decode(file_get_contents("php://input"));
$categories = $json->categories;

dataType은 json이므로 jQuery는 다음과 같이 게시합니다.

{"categories":"[{\"id\":21,\"children\":[{\"id\":196},{\"id\":195},{\"id\":49},{\"id\":194}]},{\"id\":29,\"children\":[{\"id\":184},{\"id\":152}]},...]"}

표준 url 인코딩되지 않았으므로 $_POST가 비어 있습니다.

복잡한 구조에 데이터를 설정할 수 있으며 jQuery가 올바르게 인코딩합니다.

$('#save').click(function() {
  $.ajax({
    type: 'POST',
    url: 'save_categories.php',
    dataType: 'json',
    data: $('.dd').nestable('serialize'),
    success: function(msg) {
      alert(msg);
    }
  });
});

그리고 php로:$categories = json_decode(file_get_contents('php://stdin'));

시도해 보기:

$('#save').click(function() {
  var tmp = JSON.stringify($('.dd').nestable('serialize'));
  // tmp value: [{"id":21,"children":[{"id":196},{"id":195},{"id":49},{"id":194}]},{"id":29,"children":[{"id":184},{"id":152}]},...]
  $.ajax({
    type: 'POST',
    url: 'save_categories.php',
    dataType: 'json',
    data: 'categories=' + encodeURIComponent(tmp),
    success: function(msg) {
      alert(msg);
    }
  });
});

저는 이 대사만 바꿨습니다.

data: 'categories=' + encodeURIComponent(tmp),

왜냐하면 그것이 당신이 그곳에서 어떻게 데이터를 써야 하는지에 대한 방법이기 때문입니다.내가 테스트해봤는데, 작동이 되네요...

언급URL : https://stackoverflow.com/questions/19976627/posting-json-with-jquery-ajax-to-php

반응형