使用PHP Curl获取运费及前端AJAX交互的技术问题咨询
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
errorcallback 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.,15000becomes15.000in 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

