对php脚本进行异步调用


Making an asychronus call to a php script

我有一个脚本运行在我的服务器上,需要通过URL交付的增值税号码,并检查它

(注意url被分成两个值,前2个字母和它后面的所有数字,因为VIES(增值税检查器)使用这两个变量。脚本工作得很好(我已将其包含在问题下面以供参考)。

(website)/vatchecker.php?vat=xx1234567

返回{" is_valid ":true}或{" is_valid ":false}

现在,我的网站上有一个表单,包含以下字段
<input type=“text” name=“vat_number” id=“vat_number”>
<input type=“text” name=“vat_number_confirmed” id=“vat_number_confirmed”>
and
<input type=“hidden” name=“vat_ok” id=“vat_ok” value=“0”>

最后是一个消息框

<div id=“vat-ok” style=“display:none;”>Your VAT is ok</div>
<div id=“vat-error” style=“display:block;”>Your VAT is not valid</div>

这个网站是PHP的,我已经写了很多代码

我的场景,只要字符在字段vat_number中键入,我想做一个异步调用vat_checkers.php与正在进行的值在vat_number中键入并检查它。这应该是实时的,并且每次有输入时都是恒定的。当它为真时,它被保存,并做下面列出的其他一些事情。

$(‘#vat_number’).on('input', function() {
    // do my check on vat checker.php with vat=$(“#vat_number”).val()
    // when returned response is {“is_valid”:true}
        (
            document.getElementById(“vat_ok”).value = “1”;
            document.getElementById(“vat_number_confirmed”).value = $(“#vat_number”).val()
            $(“#vat_number”).attr(“disabled”, true);
            $(“#vat-ok”).show();
            $(“#vat-error”).hide();
    });

谁能告诉我如何把所有这些块放在一起成一个工作方法,因为我的大脑将无法掌握这最后的链接。事先感谢您的帮助

供参考…GitHub上的增值税验证器

<?php
class VatValidator
{
    public $response;
    protected $soap;
    // WSDL VIES Url Service.
    protected static $url_vies = 'http://ec.europa.eu/taxation_customs/vies/checkVatService.wsdl';
    // Valid european countries ISO codes.
    protected static $european_countries = array(
        'AT', 'BE', 'BG', 'CY', 'CZ', 'DE', 'DK', 'EE', 'ES', 'FI', 'FR', 'GB', 'GR', 'HU', 'IE', 'IT', 'LT', 'LU', 'LV', 'MT', 'NL', 'PL', 'PT', 'RO', 'SE', 'SI', 'SK'
    );
    public function __construct ()
    {
        $this->soap = new SoapClient( self::$url_vies );
    }
    /**
     * Check if it's a valid vat number.
     */
    public function checkVat ( $country, $number )
    {
        $response = array( 'is_valid' => false );
        $vat = $this->prepareVat( $country, $number );
        if ($vat)
        {
            $this->response = array( 'is_valid' =>$this->soap->checkVat( $vat )->valid );
        }
        return json_encode( $this->response );
    }
    /**
     * Checks that there are all needed params ( Code Country and number );
     */
    protected function prepareVat( $country, $number )
    {
        try
        {
            if ( empty( $country ) || empty( $number ) )
            {
                throw new Exception( "Both 'country' and 'number' params are mandatory" );
            }
            if ( !in_array( $country, self::$european_countries ) )
            {
                throw new Exception( "Invalid country" );
            }
            $vat = array(
                'vatNumber'     => $number,
                'countryCode'   => $country,
            );
            return $vat;
        }
        catch( Exception $e )
        {
            $this->response = array( 'error_message' => $e->getMessage() );
            return false;
        }
    }
}
// API Call
$vies = new VatValidator();
if ($_GET['vat']) {
    $vat = $_GET['vat'];
    $country = substr($vat, 0, 2);
    $number = substr($vat, 2);
} else {
    $country = "";
    $number = "";
}
$vies->checkVat( strtoupper( $country ), $number);
$response = json_encode( $vies->response);
echo $response;
?>

编辑:这是我最后的解决方案,结合上面链接的文章和下面一个用户的反馈

<script>
    var searchRequest = null;

    $(function () {
        var minlength = 4;
        $("#jform_company_vat_tmp").keyup(function () {
            value = $(this).val();
            if (value.length >= minlength ) {
                if (searchRequest != null)
                    searchRequest.abort();
                    searchRequest = $.get("(website)/vies.php", { vat: value } )
                    .done(function(data) {
                        console.log(data);
                        checkBit = JSON.parse(data);
                        for (var key in checkBit) {
                            console.log(checkBit[key]);
                        }
                        if (checkBit[key] == true) {
                            $("#vat_switch").val(1);
                            $("#vat_number_confirmed").val($("#jform_company_vat_tmp").val());
                            $("#jform_company_vat_tmp").prop( "disabled", true );
                            $(".vat-is-ok").show();
                            $(".vat-is-not-ok").hide();
                        }
                    });
            }
        });
    });
</script>

阅读这个问题,我假设您已经从PHP文件中获得了正确/错误的响应。

$.get("vatchecker.php", { vat: "xx1234567" } )
    .done(function(data) {
        if (data === "true") {
            $("#vat_ok").val(1);
            $("#vat_number_confirmed").val($("#vat_number").val());
            $("#vat_number").addClass("disabled");
            $("#vat-ok").show();
            $("#vat-error").hide();
        }
});