contentType: "application/json" 타입으로 api 보내기

yesrin·2023년 7월 20일

Javascript

목록 보기
2/3

내 요청을 받을 컨트롤러 형식

List<Long> productList

내가 보내고 싶은 request api 형식

{
  "productList": [1, 2, 3, 4, 5]
}

ajax 사용

    function sendCartToApi() {
        if (cartItems.length > 0) {
            // Extract only the productIds from the cartItems array and convert them to long integers
            const productIds = cartItems.map(item => item.productId);

            // Create the request data object
            const requestData = {
                productList: productIds,
            };

            // Implement your API request logic here using $.ajax() method
            $.ajax({
                url: otherHost + "/orders",
                type: "POST",
                contentType: "application/json",
                data: JSON.stringify(requestData),
                success: function (data) {
                    // Handle API response if needed
                    console.log("Order placed successfully!");
                },
                error: function (error) {
                    console.error("Error placing order:", error);
                },
            });
        }
    }

아래형식으로는
contentType: "application/json" 을 설정 할 수 없음.

function sendCartToApi() {
  if (cartItems.length > 0) {
    // Extract only the productIds from the cartItems array and convert them to long integers
    const productIds = cartItems.map(item => item.productId);

    // Implement your API request logic here
    // You can use jQuery's $.ajax() or $.post() for the AJAX request
    $.post(otherHost + "/orders", { productList: productIds })
      .done(function (data) {
        // Handle API response if needed
        console.log("Order placed successfully!");
      })
      .fail(function (error) {
        console.error("Error placing order:", error);
      });
  }
}
profile
안녕하세요! 틀린 정보는 댓글 달아 주세요.

1개의 댓글

comment-user-thumbnail
2023년 7월 20일

잘 봤습니다. 좋은 글 감사합니다.

답글 달기