且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-11-25 15:28:58

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


  • 您可以使用分页来获取部分数据每一次。加载的数据少于
    ,数据加载得越快。而你的应用程序将更多地响应用户的操作。这个解决方案对于用户而言是一个诀窍,因为它实际上比以前需要更多的时间来加载所有数据。

  • 您可以保留之前加载的数据,因此当您点击回到一个按钮,
    它不会再次加载数据。但是,只有在每次点击之间数据
    变化不大时才能使用。第一次点击按钮上的
    时,它将会和以前一样,但是下一次,
    会立即显示。



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


Using jQuery to call an endpoint and populate the data on the frontend is a common task. After searching and using multiple solutions the below is my current blueprint for any ajax calls.

How can I improve the following to be faster and more efficient? I realize doing it in pure javascript will be faster but at this point I assume jQuery will be present.

Frontend - 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 );
        });
    });
});

Frontend - 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>

Backend - 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;

I don't think that this code can be more efficient in jQuery. But you have some options left to give a more efficient feeling :

  • You can use pagination to get a portion of your data each time. The
    less data to load, the quicker it get. And your application will be
    more responsive to the user's actions. This solution is a trick for the user, because it will take in reality more time than before to load all the data.
  • You can keep previous loaded data so when you click back on a button, it won't load again the data. But, this can only be used if the data won't change much between each click. The first time you will click on a button, it will take the same time as before, but the next time, it will be immediat.

Be aware that the more HTML code you load, the more it will take time to initiate JavaScript behavior on it.