在将Rest Based API集成到我现有的WordPress网站时,我遇到了一些麻烦。 API前端由PHP,HTML和JQuery代码组成。
我已经将API zip文件夹中的文件上传到了我的Web服务器,并且设法成功连接了API。我可以看到对API的请求成功完成了。
但是,从我的WordPress前端开始,我通过使用“插入PHP”插件将我的API的“ index.php”文件包含到我的WordPress网站中。
当我尝试填写表单字段,然后单击“提交”按钮时,在向API提出请求后,应该显示条件结果。
相反,我收到以下错误消息(来自Google Chrome控制台中的控制台。
VM78:1 Uncaught SyntaxError: Unexpected token < in JSON at position 0
at Function.parse [as parseJSON] (<anonymous>)
at buildResults (availability.js:142)
at Object.success (availability.js:122)
at fire (jquery.js:2913)
at Object.fireWith [as resolveWith] (jquery.js:3025)
at done (jquery.js:7400)
at XMLHttpRequest.<anonymous> (jquery.js:7822)
我已经正确地将JS文件放入主题的我的functions.php文件中。我还尝试过创建WordPress自定义页面模板文件,并将API集成到自定义页面后,API检查器运行正常。
但是,当我将API检查器集成到我的网站首页(通过使用PHP Include)时,会抛出上述JQuery错误。
只是想知道是否有人对我如何解决这个问题有任何潜在的想法?我知道,一般来讲,以上错误表明应在使用Java脚本时返回HTML。
但是对于将API检查器成功集成到我的WordPress主页上应该采取的其他步骤,我有些迷惑。我要求在主页上显示API检查器的原因是因为我正在使用Visual Composer围绕基于API的检查器定制设计。
不幸的是,我真的不能依靠自定义页面模板,因为我需要能够使用Visual Composer插件来围绕API检查器起草设计。
任何解决方案都将受到欢迎! :-) 谢谢, -乔什。
-关联的JS代码-
// Validates form input and sends the availability request.
function checkRequest() {
// Reset all form values and hide results
resetAllValues();
$('#results').hide();
$('#addressDiv').hide();
loadingTimer('#searchButton', true);
// Get checker type radio selection
var action = $('input[name=action]:radio:checked').val();
var errorMessage = '';
// Remove input validation highlight
$('.form-control').each(function () {
$(this).removeClass('input-highlight');
});
if (action == 'cli_checker') {
// Validate cli
var cli = $('#cliInput').val();
cli = cli.replace(/\+|\(|\)|\-|\s/gi, '');
if (/^0[0-9]{9,15}$/.test(cli)) {
// Show results loading
$('#results').fadeIn('slow');
$('#statusTbl').show();
$('#availableProducts').show();
// Send availability request
availabilityRequest(cli);
}
else {
// Display validation error dialog
errorMessage = 'Telephone number is invalid.';
$('#cliInput').addClass('input-highlight');
displayValidationErrorDialog(errorMessage);
}
}
else {
// Validate postcode
var postcode = $('#postcodeInput').val();
postcode = postcode.replace(/\+|\(|\)|\-|\s/gi, '');
if (validatePostcode(postcode)) {
// Send address search request
addressRequest(postcode);
}
else {
// Display validation error dialog
errorMessage = 'Postcode is invalid.';
$('#postcodeInput').addClass('input-highlight');
displayValidationErrorDialog(errorMessage);
}
}
}
// Checks if a string is a valid postcode.
function validatePostcode(postcode) {
var postcode = $('#postcodeInput').val();
postcode = postcode.replace(/\+|\(|\)|\-|\s/gi, '');
if (/^[A-Za-z]{1,2}(\d{1,2}|[I])[A-Za-z]? ?\d[A-Za-z]{2}$/.test(postcode))
return true;
else
return false;
}
// Display validation error message in dialog box.
function displayValidationErrorDialog(errorMessage) {
if (errorMessage.length > 0) {
var dialog = $('#console-dialog');
dialog.find('.modal-title').html('Some problems occured...');
message = '<p>Some information was entered incorrectly. The incorrect fields are listed below, and have been outlined in <span style="color:blue">blue</span> on the page.</p>';
message += '<p>' + errorMessage + '</p>';
dialog.find('.modal-body').html(message);
dialog.modal('show');
}
}
// Sets the selected text input field.
function changeInputSelection(buttonId) {
$('.form-control').each(function () {
if ($(this).attr('id') == buttonId + 'Input') {
$(this).focus();
}
});
}
// Sets the selected radio input.
function changeCheckerRadio(buttonId) {
$('.form-control').each(function () {
if ($(this).attr('id') != buttonId + 'Input') {
$(this).removeClass('input-highlight');
$(this).val('');
}
});
$('#type_phone').prop('checked', (buttonId == 'cli'));
$('#type_postcode').prop('checked', (buttonId != 'cli'));
}
// Requests availability for a postcode or phone number.
function availabilityRequest(cli) {
// Send AJAX request for availability
jQuery.ajax({
url: '?action=availability-cli',
dataType: 'text',
data: {
cli: cli,
},
success: function (result) {
$('#resultsTitle').html(cli);
buildResults(result);
loadingTimer('#searchButton', false);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
showErrorMessage(XMLHttpRequest.responseText);
}
});
}
// Displays API exception messages.
function showErrorMessage(message) {
// Display error message
$('#errorText').html('<p class=\'alert alert-error\'>' + message + '</p>');
$('#errorText').show();
}
// Updates the product availability results table with the API response.
function buildResults(jsonString) {
// Parse availability results into object
var result = jQuery.parseJSON(jsonString);
// Display End Request information
$('#status').html(result.endrequest.status);
$('#message').html(result.endrequest.message);
$('#exCode').html(result.endrequest_code);
$('#exName').html(result.endrequest_name);
// Loop through product availability results
for (var i = 0; i < result.products.length; i++) {
// Get product availability
var product = result.products[i];
var availability = (product.availability == true) ? 'Available' : 'Not Available';
var fetchdata = null;
if (product.likely_down_speed != null)
fetchdata = product.likely_down_speed.toFixed(1);
if (product.likely_up_speed != null)
fetchdata = fetchdata + ' (' + product.likely_up_speed.toFixed(1) + ')';
if (fetchdata == null)
fetchdata = 'Not Available';
// Update results table
if (product.name == 'Product One') {
$('#productoneAvail').html(availability);
$('#productone').html(fetchdata);
}
else if (product.name == 'Product Two') {
$('#producttwoAvail').html(availability);
$('#producttwo').html(fetchdata);
}
else if (product.name == 'Product Three') {
$('#productthreeAvail').html(availability);
$('#productthree').html(fetchdata);
}
else if (product.name == 'Product Four') {
$('#productfourAvail').html(availability);
$('#productfour').html(fetchdata);
}
else if (product.name == 'Product Five') {
$('#productfiveAvail').html(availability);
$('#productfive').html(fetchdata);
}
else if (product.name == 'Product Six') {
$('#productsixAvail').html(availability);
$('#productsix').html(fetchdata);
}
else if (product.name == 'Product Seven') {
$('#productsevenAvail').html(availability);
$('#productseven').html(fetchdata);
}
}
}
// Requests addresses by postcode.
function addressRequest(postcode) {
// Send AJAX request for address search by postcode
jQuery.ajax({
url: '?action=address-search',
dataType: 'text',
data: {
postcode: postcode
},
success: function (result) {
buildAddressResults(result);
$('#addressDiv').fadeIn('slow');
loadingTimer('#searchButton', false);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
showErrorMessage(XMLHttpRequest.responseText);
}
});
}
// Builds the address search results table from the API response.
function buildAddressResults(jsonString) {
var addressDiv = document.getElementById('addressDiv');
var result = jQuery.parseJSON(jsonString);
var addressHtml = '';
// There are no address search results for the postcode
if (result.addresses.length == 0) {
$('#errorText').html('<p class=\'alert alert-error\'>No addresses match this postcode.</p>');
$('#errorText').show();
return;
}
// Build address table
addressHtml += '<table class="content-table table-curved" style="width:65%; margin:0 auto; margin-top: 12px;">';
// Loop through address results
for (var i = 0; i < result.addresses.length; i++) {
var address = result.addresses[i];
// Get address fields
var subPremises = address.sub_premises === null ? "" : address.sub_premises;
var premisesName = address.premises_name === null ? "" : address.premises_name;
var thoroughfareNumber = address.thoroughfare_number === null ? "" : address.thoroughfare_number;
var thoroughfareName = address.thoroughfare_name === null ? "" : address.thoroughfare_name;
var locality = address.locality === null ? "" : address.locality;
var postTown = address.post_town === null ? "" : address.post_town;
var postcode = address.postcode === null ? "" : address.postcode;
var districtId = address.district_id === null ? "" : address.district_id;
var nad_key = address.nad_key === null ? "" : address.nad_key;
// Construct full address
var fullAddress = '';
if (subPremises != '') { fullAddress += subPremises + ' '; }
if (premisesName != '') { fullAddress += premisesName + ', '; }
if (thoroughfareNumber != '') { fullAddress += thoroughfareNumber + ' '; }
if (thoroughfareName != '') { fullAddress += thoroughfareName + ', '; }
if (postTown != '') { fullAddress += postTown + ', '; }
if (postcode != '') { fullAddress += postcode; }
// Build address result table row
addressHtml += '<tr>' +
'<td>' +
'<input onclick=\'selectAddress(event)\' type=\'radio\' id=\'addressId' + i + '\' name=\'addressId\' value=\'' + i + '\' />' +
'<input type=\'hidden\' id=\'subPremises' + i + '\' name=\'subPremises\' value=\'' + subPremises + '\' />' +
'<input type=\'hidden\' id=\'premisesName' + i + '\' name=\'premisesName\' value=\'' + premisesName + '\' />' +
'<input type=\'hidden\' id=\'thoroughfareNumber' + i + '\' name=\'thoroughfareNumber\' value=\'' + thoroughfareNumber + '\' />' +
'<input type=\'hidden\' id=\'thoroughfareName' + i + '\' name=\'thoroughfareName\' value=\'' + thoroughfareName + '\' />' +
'<input type=\'hidden\' id=\'postTown' + i + '\' name=\'postTown\' value=\'' + postTown + '\' />' +
'<input type=\'hidden\' id=\'postcode' + i + '\' name=\'postcode\' value=\'' + postcode + '\' />' +
'<input type=\'hidden\' id=\'districtId' + i + '\' name=\'districtId\' value=\'' + districtId + '\' />' +
'<input type=\'hidden\' id=\'nad_key' + i + '\' name=\'nad_key\' value=\'' + nad_key + '\' />' +
'</td>' +
'<td>' +
'<label id=\'addressLabel' + i + '\' for=\'addressId' + i + '\'>' + fullAddress + '</label>' +
'</td>' +
'</tr>';
}
// None of the above addresses - search by postcode input
addressHtml += '<tr>' +
'<td className=\'table\'>' +
'<input onclick=\'selectAddress(event)\' type=\'radio\' id=\'addressId-1\' name=\'addressId\' value=\'-1\' />' +
'<td className=\'table\'>' +
'<label for=\'addressId-1\'>None of the above</label>' +
'</td>' +
'</tr>';
addressHtml += '</table>';
addressDiv.innerHTML = addressHtml;
}
// Select address event handler.
function selectAddress(event) {
// Get the targetnode that fired the event
var target = $(event.target);
// Get the selected address
var addressId = target.val();
// Show results loading
$('#addressDiv').hide();
$('#statusTbl').show();
$('#availableProducts').show();
$('#results').fadeIn('slow');
loadingTimer('#searchButton', true);
// Send request for availability by exact address
addressAvailabilityRequest(addressId);
}
// Requests availability for address result table id or by postcode if none is selected.
function addressAvailabilityRequest(addressId) {
// Check if we need to do a postcode check and exit function
if (addressId == -1) {
var postcode = $('#postcodeInput').val();
availabilityRequest(postcode);
return;
}
// Address has been selected from results table
if (addressId != '') {
// Get address fields from hidden form input
subPremises = document.getElementById('subPremises' + addressId).value;
premisesName = document.getElementById('premisesName' + addressId).value;
thoroughfareNumber = document.getElementById('thoroughfareNumber' + addressId).value;
thoroughfareName = document.getElementById('thoroughfareName' + addressId).value;
postTown = document.getElementById('postTown' + addressId).value;
postcode = document.getElementById('postcode' + addressId).value;
districtId = document.getElementById('districtId' + addressId).value;
nad_key = document.getElementById('nad_key' + addressId).value;
// Construct API request URL
var address = {
sub_premises: subPremises,
premises_name: premisesName,
thoroughfare_number: thoroughfareNumber,
thoroughfare_name: thoroughfareName,
post_town: postTown,
postcode: postcode,
district_id: districtId,
nad_key: nad_key
};
var data = {
address: JSON.stringify(address)
}
// Send AJAX request for availability for specified address
jQuery.ajax({
url: '?action=availability-exact',
dataType: 'text',
type: 'POST',
data: data,
success: function (result) {
$('#resultsTitle').html($('#addressLabel' + addressId).html());
buildResults(result);
loadingTimer('#searchButton', false);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
showErrorMessage(XMLHttpRequest.responseText);
}
});
}
}
// Sets search button loading state.
function loadingTimer(targetNode, start) {
if (start) {
$(targetNode).html('Searching...');
}
else {
$(targetNode).html('<span class="glyphicon glyphicon-search"></span> Search');
}
}
// Resets all search results.
function resetAllValues() {
var loadingImg = "<img src='eligibility/images/spinner.gif' alt='checking' />";
// Reset error text
$('#errorText').hide();
// Reset address
$('#addressDiv').html('');
// Reset title
$('#resultsTitle').html('');
// Reset all elements to loading
$('#status').html(loadingImg);
$('#message').html(loadingImg);
$('#exCode').html(loadingImg);
$('#exName').html(loadingImg);
$('#productoneAvail').html(loadingImg);
$('#producttwoAvail').html(loadingImg);
$('#productthreeAvail').html(loadingImg);
$('#productfourAvail').html(loadingImg);
$('#productfiveAvail').html(loadingImg);
$('#productsixAvail').html(loadingImg);
$('#productsevenAvail').html(loadingImg);
$('#productone').html(loadingImg);
$('#producttwo').html(loadingImg);
$('#productthree').html(loadingImg);
$('#productfour').html(loadingImg);
$('#productfive').html(loadingImg);
$('#productsix').html(loadingImg);
$('#productseven').html(loadingImg);
}