这是我当前的jQuery onclick函数,用于向外部API发出AJAX请求,然后在div中显示结果。我如何实现一个回调函数,允许 response.vehicle 值可用于另一个填充单独div的函数,点击页面下方?
$("#get-rego").click(function(e) {
e.preventDefault();
ajaxLoader.style.display = "block";
plate = document.getElementById("input_2_6").value;
var requestData = $.post({
url: "/wp-admin/admin-ajax.php",
data: {
"action": "get_vehicle",
"plate": plate,
},
"dataType": "json"
});
requestData.done(function(obj) {
var response = obj.idh;
var vehicleMake,
vehicleModel,
vehicleYear,
vehicleColour,
vehicleSubModel,
vehicleBodyStyle;
ajaxLoader.style.display = "none";
vehicleDetails.style.display = "block";
vehicleMake = response.vehicle.make;
vehicleModel = response.vehicle.model;
vehicleYear = response.vehicle.year_of_manufacture;
vehicleColour = response.vehicle.main_colour;
vehicleSubModel = response.vehicle.submodel;
vehicleBodyStyle = response.vehicle.body_style;
vehicleDataSummaryOutput = "<div class=\"summary\">" +
"<ul>" +
"<li><span class=\"label\">Make:</span> " + vehicleMake + "</li>" +
"<li><span class=\"label\">Model:</span> " + vehicleModel + "</li>" +
"<li><span class=\"label\">Year:</span> " + vehicleYear + "</li>" +
"<li><span class=\"label\">Colour:</span> " + vehicleColour + "</li>" +
"<li><span class=\"label\">Submodel:</span> " + vehicleSubModel + "</li>" +
"<li><span class=\"label\">Body Style:</span> " + vehicleBodyStyle + "</li>" +
"</ul>" +
"</div>";
vehicleDataSummary.innerHTML = vehicleDataSummaryOutput;
});
requestData.fail(function( jqXHR, textStatus ) {
alert( "Request failed: " + textStatus );
});
});
答案 0 :(得分:0)
您可以使用以下代码:
$.ajax({
url: '/wp-admin/admin-ajax.php',
dataType: 'json',
success: function (response) {
// Parse responseText
var obj = JSON.parse(response.responseText);
// Pass object to function
doSomeThing(obj.vehicle);
}
});
function doSomeThing(vehicle)
{
// Do some work ...
}