【发布时间】:2018-04-25 14:44:13
【问题描述】:
我的 WordPress AJAX 进程已成功完成,但返回的 JSON 对象在 Chrome Devtools 中显示以下错误:未捕获的类型错误:无法读取未定义的属性“车辆”。我不确定为什么会这样。解析的 JSON 数据作为对象输出,应该是正确的。下面详细介绍了所有 JavaScript 和 PHP 代码。可在此处查看示例有效 JSON 对象:https://jsfiddle.net/roaq9ew1/。
/**
* Create 'Get Registration' button and append to vehicle-registration list item
*/
var getRegoButton = document.createElement('button');
getRegoButton.setAttribute('id', 'get-rego');
getRegoButton.setAttribute('class', 'get-rego');
getRegoButton.innerHTML = 'Get Registration';
var vehicleRegistrationWrapper = document.getElementById('field_2_6');
vehicleRegistrationWrapper.appendChild(getRegoButton);
/**
* Function to retrieve Carjam API data via AJAX
*/
jQuery(document).ready( function($){
$(".vehicle-details").hide();
$("#get-rego").click(function(e){
e.preventDefault();
$(".vehicle-details").show();
plate = $("#input_2_6").val();
$.post(
"/wp-admin/admin-ajax.php",
{
"action": "get_vehicle",
"plate": plate,
},
function(response) {
obj = JSON.parse(response);
console.log(typeof obj);
console.log(obj.idh.vehicle);
}
);
});
function populateVehicleDetails(vehicleDetail, apiData) {
var carData = ".vehicle-details span id="+vehicleDetail+"";
$(carData).val(apiData);
}
});
/**
* Function to handle API call to Carjam for vehicle registration data
*/
add_action( 'wp_ajax_get_vehicle', 'prefix_ajax_get_vehicle' );
add_action('wp_ajax_nopriv_get_vehicle', 'prefix_ajax_get_vehicle');
function prefix_ajax_get_vehicle() {
$plate = $_POST["input_2_6"];
$testApikey = "C9DBAF2CD487DE38EC1AE78C09329E6711BF644C";
$testApiUrl = "http://test.carjam.co.nz/api/car/?plate=";
$url = $testApiUrl.$plate."&key=".$testApiKey;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($ch);
curl_close($ch);
$oXML = new SimpleXMLElement($data);
echo json_encode($oXML);
wp_die();
}
【问题讨论】:
标签: javascript php jquery json ajax