使用 jQuery 调用 PHP 端点的最有效方法


Most efficient way to call a PHP endpoint using jQuery

使用 jQuery 调用端点并在前端填充数据是一项常见的任务。在搜索和使用多个解决方案后,以下是我当前任何 ajax 调用的蓝图。

如何改进以下内容以使其更快、更高效?我意识到在纯javascript中这样做会更快,但在这一点上,我认为jQuery将存在。

前端 - Javascript:

$(document).ready(function()
{
    function callEndpoint( call_url, payload ){
        return $.ajax({
            url: call_url,
            type: 'GET',
            data: payload
        });
    }
    $( '.get-endpoint' ).click( function() {
        sSelected = $( this ).text();
        console.log( sSelected );
        oRequest = callEndpoint( '/play/endpoint2.php', { 'type': sSelected } );
        oRequest.done(function( sJson ) {
            aData = JSON.parse( sJson );
            $( '.from-endpoint' ).text( aData.text );
        });
    });
});

前端 - html:

<body>
    <button class="get-endpoint">Games</button>
    <button class="get-endpoint">Books</button>
    <button class="get-endpoint">Comics</button>
    <div class="from-endpoint">Coming soon...</div>
</body>

后端 - PHP:

$aReturn[ 'text' ] = '';
if( !empty( $_GET ) )
{
    if( $_GET[ 'type' ] == 'Games' )
    {
        $aReturn[ 'text' ] = 'Text for games';
    }
    else if( $_GET[ 'type' ] == 'Books' )
    {
        $aReturn[ 'text' ] = 'Text for books';
    }
    else if( $_GET[ 'type' ] == 'Comics' )
    {
        $aReturn[ 'text' ] = 'Text for comics';
    }
}
$sJson = json_encode( $aReturn, 1 );
header( 'Content-Type: application/json' );
echo $sJson;

我不认为这段代码在jQuery中更有效率。但是您还有一些选择可以给人更有效的感觉:

  • 每次都可以使用分页来获取部分数据。这
    要加载的数据越少,获取的速度就越快。您的应用程序将是
    对用户操作的响应速度更快。此解决方案是一个技巧用户,因为实际上加载所有数据需要比以前更多的时间。
  • 您可以保留以前加载的数据,以便在单击按钮后退时,它不会再次加载数据。但是,这只能在数据中使用每次点击之间不会有太大变化。第一次点击在按钮上,它将花费与以前相同的时间,但下一次,这将是立竿见影的。

请注意,您加载的 HTML 代码越多,在其上启动 JavaScript 行为所需的时间就越长。

看起来您的类别不会经常更改。 您可以通过使用 JavaScript 本地存储或 cookie 来缓存数据来节省一些带宽。 如果您计划在某个时候连接到 mysql 数据库,则可以使用 StorageProcedure,它们是可变的预编译语句。

既然你无论如何都要使用JSON和jQuery,我建议你应该看看jQuery的getJSON方法。我觉得它会减少一些代码行,尽管我不确定它是否有助于它变得更有效率。无论如何,getJSON只是AJAX的简写,我想我应该建议这个。

对于 AJAX 数据传输浏览器>服务器>浏览器来说,这可能是一个好方法。希望它符合您的需求。

jQuery

$( function () {
    function fetch( data ) {
        var encoding = data.encoding,
            url = data.url,
            params = data.params,
            type = ( data.type ) ? : 'GET',
            cache = ( data.cache ) ? : 'false',
            async = ( data.async ) ? : 'true';
        return $.ajax({
            url: url,
            async: async,
            cache: cache,
            data: params,
            dataType: encoding,
            type: type
        });
    }
    var options = {
            url: 'controller.php',
            params: {
                param_one: value_one,
                param_two: value_two,
                param_n: value_n
            },
            encoding: 'json'
        };
    // Get the JSON feed from the server
    $.when( fetch( options ) ).then( function ( response ) {
        // Is there anything in the pool?
        if ( response ) {
            // Store the response and use it in your code
            var data = response.data;
            console.log( data.responseOne );
            console.log( data.responseTwo );
        }
    });
});

PHP 控制器

// Set header to application/json
header( 'Content-type: application/json' );
// Create the DB connection object
$dbc = new mysqli( DB_HOST, DB_USER, DB_PASS, DB_NAME );
// Initialize parameters array
$params = array();
// Store the query variables in an array
$query_type = ( $_GET ) ? : $_POST;
// Run foreach and store the values in an array
foreach ( $query_type as $key => $value ) {
    $params[ $key ] = mysqli_real_escape_string( $dbc, $value );
}
// Now you can access passed parameters like $params['param_name']
// This would be the data obtained from DB or some server array processing, whatever
$response = array(
    'data' => array(
        'response_one' => 'some_value',
        'response_two' => 'another_value'
     )
);
// Encode the result
echo json_encode( $response );

如果你不想使用纯javascript,你可以用更好的选择器来改进你的jQuery代码

例如,您可以在<div class="from-endpoint">中添加id

您可以在选择器中添加标签,如下所示:

$('button.get-endpoint')
  1. 您可以删除 getEndpoint 方法,只使用 $.get 方法。

$(document).ready(function()
{
    $( '.get-endpoint' ).click( function() {
        sSelected = $( this ).text();
        console.log( sSelected );
        oRequest = $.get('/play/endpoint2.php', { 'type': sSelected });
        oRequest.done(function( sJson ) {
            aData = JSON.parse( sJson );
            $( '.from-endpoint' ).text( aData.text );
        });
    });
});

  1. 您可以使您的代码符合 lint 标准。

$(document).ready(function()
{
    $( '.get-endpoint' ).click( function() {
        var sSelected = $( this ).text();
        console.log( sSelected );
        oRequest = $.get('/play/endpoint2.php', { type: sSelected });
        oRequest.done(function( sJson ) {
            var aData = JSON.parse( sJson );
            $( '.from-endpoint' ).text( aData.text );
        });
    });
});

  1. 使用成功而不是完成并将回调移动到它自己的函数

$(document).ready(function()
{
    $( '.get-endpoint' ).click( function() {
        var sSelected = $( this ).text();
        console.log( sSelected );
        $.get(
            '/play/endpoint2.php',
            { type: sSelected },
            insertData
        );
    });
});
function insertData( sJson ) {
    var aData = JSON.parse( sJson );
    $( '.from-endpoint' ).text( aData.text );
}

  1. 使用$.getJSON而不是$.get$.ajax

$(document).ready(function()
{
    $( '.get-endpoint' ).click( function() {
        var sSelected = $( this ).text();
        console.log( sSelected );
        $.getJSON(
            '/play/endpoint2.php',
            { type: sSelected },
            insertData
        );
    });
});
function insertData( data ) {
    $( '.from-endpoint' ).text( data.text );
}