source

JQuery를 사용하여 JSON 데이터를 게시하려면 어떻게 해야 합니까?

factcode 2023. 2. 13. 20:49
반응형

JQuery를 사용하여 JSON 데이터를 게시하려면 어떻게 해야 합니까?

같은 서버의 웹 서비스에 Json을 게시하고 싶습니다.근데 JQuery를 이용해서 Json을 올리는 방법을 모르겠어요.다음 코드로 시도했습니다.

$.ajax({
    type: 'POST',
    url: '/form/',
    data: {"name":"jonas"},
    success: function(data) { alert('data: ' + data); },
    contentType: "application/json",
    dataType: 'json'
});

그러나 이 JQuery 코드를 사용하면 데이터는 서버에서 Json으로 수신되지 않습니다.서버의 예상 데이터는 다음과 같습니다.{"name":"jonas"}단, 서버가 수신하는 JQuery를 사용하여name=jonas즉, Json이 아닌 "urlencoded" 데이터입니다.

JQuery를 사용하여 urlencoded 데이터가 아닌 Json 형식으로 데이터를 게시할 수 있는 방법이 있습니까?아니면 수동으로 Ajax 요청을 사용해야 합니까?

JSON 문자열이 아닌 객체를 전달하고 있습니다.개체를 전달하면 jQuery는 개체를 이름-값 쌍으로 일련화하기 위해 사용합니다.

데이터를 문자열로 전달하면 데이터가 직렬화되지 않습니다.

$.ajax({
    type: 'POST',
    url: '/form/',
    data: '{"name":"jonas"}', // or JSON.stringify ({name: 'jonas'}),
    success: function(data) { alert('data: ' + data); },
    contentType: "application/json",
    dataType: 'json'
});

언젠가 외로운 대답을 바탕으로, 나는 그 답을 창조해냈다.jpost특정 파라미터를 랩합니다.

$.extend({
    jpost: function(url, body) {
        return $.ajax({
            type: 'POST',
            url: url,
            data: JSON.stringify(body),
            contentType: "application/json",
            dataType: 'json'
        });
    }
});

사용방법:

$.jpost('/form/', { name: 'Jonh' }).then(res => {
    console.log(res);
});

다음과 같이 ajax를 사용하여 데이터를 게시할 수 있습니다.

 $.ajax({
   url: "url", 
   type: "POST",
   dataType: "json",
   contentType: "application/json; charset=utf-8",
   data: JSON.stringify({ name: 'value1', email: 'value2' }),
   success: function (result) {
       // when call is sucessfull
    },
    error: function (err) {
    // check the err for error details
    }
 }); // ajax call closing

Ninh Pham의 솔루션을 시도했지만 수정하기 전까지는 효과가 없었습니다. 아래를 참조하십시오.콘텐츠 삭제json 데이터 입력 및 인코딩 안 함

$.fn.postJSON = function(url, data) {
    return $.ajax({
            type: 'POST',
            url: url,
            data: data,
            dataType: 'json'
        });

상위 답변은 잘 작동했지만 JSON 데이터를 변수에 저장한 후 긴 양식을 보내거나 일반적으로 대용량 데이터를 처리할 때 조금 더 깔끔하게 게시할 것을 권장합니다.

var Data = {
"name":"jonsa",
"e-mail":"qwerty@gmail.com",
"phone":1223456789
};


$.ajax({
    type: 'POST',
    url: '/form/',
    data: Data,
    success: function(data) { alert('data: ' + data); },
    contentType: "application/json",
    dataType: 'json'
});

사용.Promise체크하고 있습니다.bodyobject는 유효한 JSON입니다.약속이 아닌 경우reject반환됩니다.

var DoPost = function(url, body) {
    try {
        body = JSON.stringify(body);
    } catch (error) {
        return reject(error);
    }
    return new Promise((resolve, reject) => {
        $.ajax({
                type: 'POST',
                url: url,
                data: body,
                contentType: "application/json",
                dataType: 'json'
            })
            .done(function(data) {
                return resolve(data);
            })
            .fail(function(error) {
                console.error(error);
                return reject(error);
            })
            .always(function() {
                // called after done or fail
            });
    });
}

언급URL : https://stackoverflow.com/questions/6255344/how-can-i-use-jquery-to-post-json-data

반응형