Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/417.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 将第三方API集成到WordPress网站问题中_Javascript_Jquery_Html_Wordpress_Rest - Fatal编程技术网

Javascript 将第三方API集成到WordPress网站问题中

Javascript 将第三方API集成到WordPress网站问题中,javascript,jquery,html,wordpress,rest,Javascript,Jquery,Html,Wordpress,Rest,我在将基于Rest的API集成到我现有的WordPress网站时遇到了一些问题。API前端由PHP、HTML和JQuery代码组成 我已将API zip文件夹中的文件上载到我的web服务器,并成功连接了API。我可以看到对API的请求正在成功进行,这非常好 然而,在我的WordPress前端,我通过使用“Insert php”插件将API的“index.php”文件包含到我的WordPress网站中 当我尝试填写表单字段,然后单击Submit按钮时,在向API发出请求后,应该会显示一个有条件的结

我在将基于Rest的API集成到我现有的WordPress网站时遇到了一些问题。API前端由PHP、HTML和JQuery代码组成

我已将API zip文件夹中的文件上载到我的web服务器,并成功连接了API。我可以看到对API的请求正在成功进行,这非常好

然而,在我的WordPress前端,我通过使用“Insert php”插件将API的“index.php”文件包含到我的WordPress网站中

当我尝试填写表单字段,然后单击Submit按钮时,在向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)
VM78:1未捕获的语法错误:JSON中位置0处的意外标记<
在Function.parse[as parseJSON]()
在buildResults上(availability.js:142)
at Object.success(availability.js:122)
失火(jquery.js:2913)
在Object.fireWith[as resolveWith](jquery.js:3025)
完成时(jquery.js:7400)
在XMLHttpRequest上(jquery.js:7822)
我已经将JS文件正确地放入主题的functions.php文件中。我还尝试创建WordPress自定义页面模板文件,在将API集成到自定义页面后,API检查器工作正常

但是,当我将API检查器集成到我的网站主页时(通过使用PHPClude),就会抛出上面的JQuery错误

我只是想知道是否有人对我如何解决这个问题有任何潜在的想法?我知道,一般来说,上面的错误表明HTML是在Javascript应该出现的时候返回的

但是我有点不知道我应该采取什么其他步骤来将API检查器成功集成到我的WordPress主页上。我要求API检查器显示在我的主页上的原因是因为我正在使用Visual Composer围绕基于API的检查器定制设计

因此,不幸的是,我不想依赖自定义页面模板,因为我需要能够使用Visual Composer插件围绕API检查器起草设计

欢迎任何解决方案!:-) 谢谢 -乔希

--关联的JS代码--

//验证表单输入并发送可用性请求。
函数checkRequest(){
//重置所有表单值并隐藏结果
重置所有值();
$(“#结果”).hide();
$('#addressDiv').hide();
loadingTimer(“#searchButton”,true);
//获取棋盘格类型的无线电选择
var action=$('input[name=action]:radio:checked').val();
var errorMessage='';
//删除输入验证突出显示
$('.form控件')。每个(函数(){
$(this.removeClass('input-highlight');
});
如果(操作=='cli\u checker'){
//验证cli
var cli=$('#cliInput').val();
cli=cli.replace(/\+\(\\)\-\\\s/gi',);
if(/^0[0-9]{9,15}$/.test(cli)){
//显示加载结果
$('结果').fadeIn('慢');
$('#statusTbl').show();
$(“#可用产品”).show();
//发送可用性请求
可用性请求(cli);
}
否则{
//显示验证错误对话框
errorMessage='电话号码无效';
$('#cliInput').addClass('input-highlight');
displayValidationErrorDialog(错误消息);
}
}
否则{
//验证邮政编码
var postcode=$('#postcodeInput').val();
邮政编码=邮政编码。替换(/\+\\(\\)\-\\\s/gi',);
if(验证邮政编码(邮政编码)){
//发送地址搜索请求
地址请求(邮政编码);
}
否则{
//显示验证错误对话框
errorMessage='邮政编码无效';
$('#postcodeInput').addClass('input-highlight');
displayValidationErrorDialog(错误消息);
}
}
}
//检查字符串是否为有效的邮政编码。
功能验证邮政编码(邮政编码){
var postcode=$('#postcodeInput').val();
邮政编码=邮政编码。替换(/\+\\(\\)\-\\\s/gi',);
如果(/^[A-Za-z]{1,2}(\d{1,2}|[I])[A-Za-z]?\d[A-Za-z]{2}$/.test(邮政编码))
返回true;
其他的
返回false;
}
//在对话框中显示验证错误消息。
函数显示ValidationErrorDialog(errorMessage){
如果(errorMessage.length>0){
变量对话框=$(“#控制台对话框”);
dialog.find('.modal title').html('出现了一些问题…');
message='某些信息输入不正确。下面列出了不正确的字段,并在页面上以蓝色列出。

'; message+=''+errorMessage+'

'; dialog.find('.modal body').html(message); dialog.modal('show'); } } //设置选定的文本输入字段。 功能更改输入选择(按钮NID){ $('.form控件')。每个(函数(){ if($(this.attr('id')==buttonId+'Input')){ $(this.focus(); } }); } //设置选定的收音机输入。 功能更改CheckerRadio(按钮ID){ $('.form控件')。每个(函数(){ if($(this.attr('id')!=buttonId+'Input')){ $(this.removeClass('input-highlight'); $(this.val(“”); } }); $('#type_phone').prop('checked',(buttonId='cli'); $(“#键入#u邮政编码”).prop('checked',(buttonId!='cli'); } //请求提供邮政编码或电话号码。 功能可用性请求(cli){ //发送AJAX可用性请求 jQuery.ajax({ url:“?操作=可用性cli”, 数据类型:“文本”, 数据:{ cli:cli, }, 成功:功能(结果){ $('#resultsttitle').html(cli);
// 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);

}