You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用PHP Curl获取运费及前端AJAX交互的技术问题咨询

How to Parse and Display Shipping Cost Data from JSON Response

Hey there! Let's get your shipping cost data properly parsed and displayed. Your current code is on the right track, but right now you're trying to dump the entire JSON object directly into the #service element (which will just show [object Object] instead of readable data). Let's fix that step by step.

First, Let's Understand the Typical RajaOngkir JSON Structure

Assuming your cek_ongkir.php returns a standard RajaOngkir response, it'll look something like this (simplified):

{
  "rajaongkir": {
    "destination_details": {
      "city_name": "Jakarta Selatan"
    },
    "results": [
      {
        "code": "jne",
        "name": "Jalur Nugraha Ekakurir (JNE)",
        "costs": [
          {
            "service": "OKE",
            "description": "Ongkos Kirim Ekonomis",
            "cost": [
              {
                "value": 15000,
                "etd": "2-3 Hari",
                "note": ""
              }
            ]
          },
          {
            "service": "REG",
            "description": "Layanan Reguler",
            "cost": [
              {
                "value": 20000,
                "etd": "1-2 Hari",
                "note": ""
              }
            ]
          }
        ]
      }
    ]
  }
}

Modified jQuery Code to Parse and Display Data

Here's how to update your AJAX success callback to loop through the data and render it nicely:

$('#kurir').change(function() { 
  var asal = $('#asal').val(); 
  var kab = $('#kabupaten').val(); 
  var kurir = $('#kurir').val(); 
  var berat = $('#berat').val(); 

  $.ajax({ 
    type : 'POST', 
    url : 'cek_ongkir.php', 
    dataType: "JSON", 
    data : {'kab_id' : kab, 'kurir' : kurir, 'asal' : asal, 'berat' : berat}, 
    success: function (jsonStr) { 
      // First, clear the service container to avoid duplicate content
      $("#service").empty();

      // Show destination city name (like you tried in the alert)
      $("#service").append(`<h4>Kota Tujuan: ${jsonStr.rajaongkir.destination_details.city_name}</h4>`);

      // Loop through each courier in the results
      $.each(jsonStr.rajaongkir.results, function(index, courier) {
        // Add courier name as a section header
        $("#service").append(`<h5>${courier.name} (${courier.code})</h5>`);
        
        // Create a list for this courier's services
        let serviceList = $('<ul></ul>');
        
        // Loop through each service/cost option for the courier
        $.each(courier.costs, function(i, costItem) {
          let cost = costItem.cost[0]; // Get the first cost entry (usually only one)
          // Add list item with service details
          serviceList.append(`
            <li>
              <strong>${costItem.service}</strong>: ${costItem.description}<br>
              Biaya: Rp ${cost.value.toLocaleString()}<br>
              Estimasi Waktu: ${cost.etd}
            </li>
          `);
        });
        
        // Add the service list to the container
        $("#service").append(serviceList);
      });
    },
    // Add error handling in case the request fails
    error: function(xhr, status, error) {
      $("#service").html('<p>Terjadi kesalahan saat memuat data ongkir. Silakan coba lagi.</p>');
      console.error('AJAX Error:', error);
    }
  }); 
});

Key Improvements Explained

  • Empty the container first: We use $("#service").empty() to make sure old data is cleared before adding new content.
  • Loop through nested arrays: The JSON has nested structures (results → costs → cost), so we use $.each() to iterate through each level and extract the relevant data.
  • Format readable HTML: We build proper HTML elements (headings, lists) to make the data easy to read instead of dumping raw objects.
  • Add error handling: The error callback lets you show a user-friendly message if the AJAX request fails, and logs details for debugging.
  • Format currency: Using toLocaleString() makes the cost value look nicer (e.g., 15000 becomes 15.000 in Indonesian locale).

Make Sure Your HTML Has a Proper Container

Just double-check that you have an element with id="service" in your HTML to hold the results, like:

<div id="service"></div>

That should do it! Now when you select a courier, you'll see a clean, organized list of shipping services with costs and delivery times.

内容的提问来源于stack exchange,提问作者HiDayurie Dave

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 03:54:20