sourcecode

formData 개체가 jquery AJAX post와 함께 작동하지 않습니까?

copyscript 2023. 11. 5. 14:55
반응형

formData 개체가 jquery AJAX post와 함께 작동하지 않습니까?

코드로 바로 이동합니다.

var formData = new FormData();

formData.append('name', dogName);
formData.append('weight', dogWeight);
formData.append('activity', dogActivity);
formData.append('age', dogAge);
formData.append('file', document.getElementById("dogImg").files[0]);
console.log(formData);

서버에 비동기적인 모든 정보를 보내기 위해 formData 객체에 몇 가지 문자열과 하나의 파일 객체를 추가합니다.

그 직후에 저는 jquery ajax 요청이 있습니다.

$.ajax({
  type: "POST",
  url: "/foodoo/index.php?method=insertNewDog",
  data: JSON.stringify(formData),
  processData: false,  // tell jQuery not to process the data
  contentType: "multipart/form-data; charset=utf-8",
  success: function(response){
     console.log(response);
  },
  error: function(){
  }
});

그래서 나는 여기서 서버에 정보를 게시하려고 하는데, 서버 php 파일에 POST의 간단한 print_r을 가지고 있어서 무엇이 통과하고 무엇이 되지 않는지 봅니다.

유감스럽게도 console.log(데이터)의 응답이 비어 있습니다.

또한 Network(네트워크) 탭에서 Header(헤더)를 선택하면 다음과 같은 빈 출력이 나타납니다.

enter image description here

(명확화를 위해서만) 성공 함수를 호출

jQuery를 통해 ajax 요청을 보낼 때 FormData를 보낼 필요가 없습니다.JSON.stringify이 양식 데이터에 대해 설명합니다.또한 파일을 보낼 때 내용 유형은 다음과 같습니다.multipart/form-data포함하여boundry- 이와 같은 것multipart/form-data; boundary=----WebKitFormBoundary0BPm0koKA

jQuery ajax를 통해 일부 파일을 포함한 FormData를 보내려면 다음 작업을 수행해야 합니다.

  • 세트data수정 없이 양식 데이터로 이동할 수 있습니다.
  • 세트processData로.false(jQuery가 자동으로 데이터를 쿼리 문자열로 변환하는 것을 방지할 수 있습니다.)
  • 셋 더contentType로.false(그렇지 않으면 jQuery가 잘못 설정하기 때문에 이 작업이 필요합니다.)

요청 내용은 다음과 같습니다.

var formData = new FormData();

formData.append('name', dogName);
// ... 
formData.append('file', document.getElementById("dogImg").files[0]);


$.ajax({
    type: "POST",
    url: "/foodoo/index.php?method=insertNewDog",
    data: formData,
    processData: false,
    contentType: false,
    success: function(response) {
        console.log(response);
    },
    error: function(errResponse) {
        console.log(errResponse);
    }
});

만약 당신이 정확하게 명백한 답변을 했는데도 여전히 일을 하지 않는다면 걱정하지 마세요.its working

아마도요.intelligence and quick wath당신에게 그것을 말하고 있습니다.not working

enter image description here

하지만 걱정하지마, 봐봐요.network tap enter image description here

그것의 작용.

이것이 당신의 시간을 절약하길 바랍니다.

//For those who use plain javascript

var form = document.getElementById('registration-form'); //id of form
var formdata = new FormData(form);
var xhr = new XMLHttpRequest();
xhr.open('POST','form.php',true);
// xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded'); 
//if you have included the setRequestHeader remove that line as you need the 
// multipart/form-data as content type.
xhr.onload = function(){
 console.log(xhr.responseText);
}
xhr.send(formdata);

언급URL : https://stackoverflow.com/questions/32421527/formdata-object-not-working-with-jquery-ajax-post

반응형