更新时间: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 :
Be aware that the more HTML code you load, the more it will take time to initiate JavaScript behavior on it.