Program Club

jQuery-Ajax를 통해 JSON을 PUT하는 방법?

proclub 2020. 12. 1. 19:58
반응형

jQuery-Ajax를 통해 JSON을 PUT하는 방법?


jQuery 와 함께 Ajax를 통해 JSON 형식의 데이터를 서버 에 넣으려고 합니다. 내 코드는 다음과 같습니다.

$.ajax({
    type: "PUT",
    url: myURL,
    contentType: "application/json",
    data: {"data": "mydata"}
});

그러나 서버 측에서는 data=mydata예상 JSON 대신 문자열을 수신합니다 . Firebug도 똑같이 말합니다.

오류는 어디에 있습니까?


데이터가 문자열이어야한다고 생각합니다. 개체는 여기에 표시되는 쿼리 문자열로 변환됩니다.

JSON.stringify(obj)메서드를 사용 하여 개체를 문자열로 변환 할 수 있습니다 . JSON 객체의 코드는 https://github.com/douglascrockford/JSON-js/blob/master/json2.js 에서 사용할 수 있습니다 .

또는 객체를 생성하는 데 사용하는 코드를 리터럴 문자열로 전달하기 만하면됩니다.하지만 이것은 단지 예일 뿐이며 이미 생성 한 일부 객체를 인코딩하고 싶을 것입니다.


애플리케이션에서 항상 JSON을 보내야하는 경우 init의 어딘가에서이를 실행 한 다음 $.ajax예제에서와 같이 기본 호출 을 사용할 수 있으며, 항상 Ajax 기본 쿼리 문자열 대신 JSON 문자열로 직렬화됩니다.

여기에서는 위에서 언급 한 JSON 개체를 사용합니다.

$.ajaxSetup({
    contentType : 'application/json',
    processData : false
});
$.ajaxPrefilter( function( options, originalOptions, jqXHR ) {
    if (options.data){
        options.data=JSON.stringify(options.data);
    }
});

//url: this is a reference to the XML, where you need to define the mapping.
//<entry key="/getEmpDetails/transEfileGenerate.app">
//<bean class="com.adp.ems.framework.spring.MappingItem" p:delegate-ref="efilePageDelegate"
//p:action="passJSONObjectAndGetWebServiceOutput" />

//str1 is the input JSON that you need to pass... Ajax will automatically take care to get the response.
//</entry>

var kw = {
    url : "getEmpDetails/transEfileGenerate.app",
    timeout : 30000,
    handleAs : "json",
    sync: false,
    putData : str1,
    headers: { "Content-Type": "application/json"},
    load : function(result) {
},

참고 URL : https://stackoverflow.com/questions/1749272/jquery-how-to-put-json-via-ajax

반응형